Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional rendering of HTML elements in React?

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.

like image 478
noob Avatar asked Nov 07 '16 16:11

noob


2 Answers

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?

like image 195
Harkat Avatar answered Sep 20 '22 14:09

Harkat


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>

    )
  }
}
like image 31
Eric Kambestad Avatar answered Sep 18 '22 14:09

Eric Kambestad