Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Passing Boolean value to component

Tags:

reactjs

I am trying to pass a Boolean value to my component so it can show an image depending on if it is true or false but I am not very sure how to proceed here.

Here is the code:

Passing Boolean value to component:

<SomeComponent showImage={false}/>

Trying to use it on component:

const TheImage = showImage => (

      <div align="center">
        {showImage ? (<img src={ImageIwant} alt="The image i want" width="80%" height="80%" />) : ''}
        <p>Here is the image</p>
      </div>); 

I am new to react an i am not sure why this doesn't work.

like image 549
Otorrinolaringologista -man Avatar asked Jan 28 '23 00:01

Otorrinolaringologista -man


2 Answers

Change your show image component from

const TheImage = showImage => (

  <div align="center">
    {showImage ? (<img src="https://lcsc.academyofmine.com/wp-content/uploads/2017/06/Test-Logo.svg.png" alt="The image i want" width="80%" height="80%" />) : ''}
    <p>Here is the image</p>
  </div>);

to

const TheImage = prop => (

  <div align="center">
    {prop.showImage ? (<img src="https://lcsc.academyofmine.com/wp-content/uploads/2017/06/Test-Logo.svg.png" alt="The image i want" width="80%" height="80%" />) : ''}
    <p>Here is the image</p>
  </div>);

Because your component will have the prop as an object so if you want to access any property which is passed you need to use prop.yourpropertyname

Demo

like image 53
Just code Avatar answered Jan 31 '23 21:01

Just code


Add curly braces to showImage to destruct it

const TheImage = { showImage } => (

      <div align="center">
        {showImage ? (<img src={ImageIwant} alt="The image i want" width="80%" height="80%" />) : ''}
        <p>Here is the image</p>
      </div>);
like image 21
Akash Salunkhe Avatar answered Jan 31 '23 22:01

Akash Salunkhe