If you want to use the conditional rendering, do not insert blocks if
within the code rendering the component. First that the way you did is incorrect and second because it is not good to insert very complex logic in code whose purpose is only to render, it is not very easy to understand and organize the code.
In this case, you want to render one component or another depending on the main
, in this case what you could do is create a function that checks the state and returns determining component, then you call this function inside the renderer code using keys {}
.
It would be something like this function I called render
, it has the logic of if/else
:
const render = () => {
if(main ==='home'){
return <One />
}
else{
return <Two />
}
}
Then, just call it inside the renderer code:
return (
<div className={"mainbody"}>
<Headerman/>
<Navbarmain setmain={setmain} />
{ render() } // <= chame ela aqui
</div>
);
See how the code you render has become simpler to understand without if/else
. Now see an executable example below that has a button Mudar o "main"
changing the state of main
and render a component <One />
or <Two />
according to the value of main
:
const { useState } = React;
function One(){
return <div>1</div>
}
function Two(){
return <div>2</div>
}
const Example = ({title}) => {
const [main, setMain] = useState('home');
const render = () => {
if(main ==='home'){
return <One />
}
else{
return <Two />
}
}
const mudarMain = () => {
if (main === "home") return setMain("")
else return setMain("home")
}
return (
<div>
<p>{title}</p>
<button onClick={mudarMain}>
Mudar o "main"
</button>
{ render() }
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Teste condicional: " />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
THANK YOU, FOR YOUR HELP, FRIEND!!!
– morata100