I am looking to render conditionally some HTML elements of my ponent.
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 am looking to render conditionally some HTML elements of my ponent.
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.
Share Improve this question asked Nov 7, 2016 at 16:52 noobnoob 6,8646 gold badges23 silver badges32 bronze badges 2- 4 nah that should definitely work. Can you post a fiddle of your example or provide more code? – azium Commented Nov 7, 2016 at 16:54
- I can confirm the ternary expression works. Can you please check the type and value of your boolean? – Akshat Mahajan Commented Nov 7, 2016 at 18:52
4 Answers
Reset to default 6I 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 plex 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./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>
)
}
}
Something like this doesn't work?
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>
)
}
}
I usually do something like the following (h/t to Chad whose code I stole & modified)
class Demo extends React.Component{
constructor(props){
super(props);
this.state = {
boolean: false
};
}
render(){
var bool = null;
if (this.state.boolean) {
bool = (<div><h1>True</h1></div>);
}
return(
<div>
{bool}
</div>
);
}
}