I am looking to render conditionally some HTML elements of my component.
I have a state variable Boolean, which can be either true (want to render text) or false (want to render nothing).
Inside the return param for the render functon, I have tried the following:
{this.state.boolean ? <div><h1>True</h1></div> : <div></div>}
{this.state.boolean && <div><h1>True</h1></div> || <div></div>}
But in both cases, the h1 element is rendered regardless of the state of Boolean!
Any ideas? Thanks in advance.
I usually do:
outputHTML(boolean) {
if(!boolean) return null;
return (
<div>
Something you wanted to show if the boolean was present
</div>
)
}
render() {
return (
<div>
{this.outputHTML(this.state.boolean)}
</div>
)
}
If the HTML you want to conditionally render has alot of conditions or is complex by nature. NOTE: Returning null will just render nothing.
Or the shorter, simpler version:
{this.state.boolean && <div><h1>True</h1></div>}
If it is not working please provide more context, maybe some error messages or something?
This definitely works, which sounds like what you've been doing.
Check the bin
https://jsbin.com/qomofonera/edit?html,js,output
class Demo extends React.Component{
constructor(props){
super(props);
this.state = {
boolean: false
};
}
render(){
return(
<div>
{this.state.boolean ? <div><h1>True</h1></div> : <div><h1>False</h1></div>}
</div>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With