arga wirawan
arga wirawan

Reputation: 237

How to make react child component using conditional

So usually we create child component of react using code seems like this :

const component =(<button>Bla Bla</button>)

How you can create that using conditional? I have to try this one :

const component =(()=>{
if(true){
return(<button>Bla Bla</button>)
}else{
return  null
}
})

but that code throw error : Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

How to write that code properly ?

Upvotes: 0

Views: 350

Answers (4)

frontendromeo
frontendromeo

Reputation: 62

const bio = this.state.displayBio ? (
  <div>
    This is true false condition
    <button onClick={this.toggleDisplay}>Show Less</button>
  </div>
) : (
  <div>
    <button onClick={this.toggleDisplay}>Show More</button>
  </div>
);

Upvotes: 0

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

You can do that by simply passing a prop to it. Make the component like:

const Button = ({ display }) => {
  return <>
   {display && <button>I am Button<button>} 

  </>
}

Now if you want to display it you can just call it as:

<Button display={true} />

Hope this works for you.

Upvotes: 3

harisu
harisu

Reputation: 1416

You can do it like this

const component = true ? (<button>Bla Bla</button>): null

true can be any conditional you want to check

Upvotes: 1

dorriz
dorriz

Reputation: 2679

    const myComp = ({value}) =>(
      <div>
       {
         value &&
          <myComp />
       }
     <div>

From my comment above. One way is to use conditional rendering in you JSX code

Upvotes: 0

Related Questions