Greetings I'm just learning React and I ran into this error
cannot be called in a class component. React hooks must be called in a react function component or a custom react hook function
this is the code
import React, {Component} from "react";
class ComponenteA extends Component{
render(){
return (
<span>ComponenteA</span>
)
}
}
class ComponenteB extends Component{
render(){
return (
<span>ComponenteB</span>
)
}
}
function useConditionalRendering (mostrarA) {
if (mostrarA){
return <ComponenteA/>
}
return <ComponenteB/>
}
export default class ConditionalSection extends Component {
constructor(){
super()
this.state={mostrarA:true}
}
render (){
return (
<div>
<h4>Conditional Render</h4>
{useConditionalRendering(this.state.mostrarA.mostrarA)}
</div>
)
}
}
I get the error in this line of code {useConditionalRendering(this.state.mostrarA.mostrarA)}
I would really appreciate your help
I recommend you switch to functional components. Still if you want to render a component depending on a condition it would have to be something like this:
Later you have to control the value of showA through a function, the props or the componentDidUpdate, or componentDidMount so that it renders one or the other
You have two options, one is to leave it as it is and place another type of validation that is not `this.state.mostrarA.mostrarA, the other option is to leave it in the functional component (recommended):
From this:
To this:
If you want to leave it as a class in your validation just use this (not recommended):