5

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.

0

3 Answers 3

5

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>);
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

1

When you don't have a component to render if the prop value is false, I would use conditional rendering with the && operator instead of an inline if statement.

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>
);

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.