Home > Software design >  display an image in react based on a response
display an image in react based on a response

Time:11-09

I want to display an icon only if the answer is yes?

{
 <div className={"options"}>
  <img src={iconteleconsult} alt={"teleconsultation"}/>
 </div>
}  
            

CodePudding user response:

here is the code sample this will help:

response
    ? <div className={"options"}>
        <img src={iconteleconsult} alt={"teleconsultation"} />
      </div>
    : null

CodePudding user response:

You can do like this way also render image conditionally.

condition && <img ... />

Example:

const { forwardRef, useState } = React;

const Parent = () => {
  const [isShowImage, setShowImage] = useState(4);

  const imageShowHandler = () => {
    setShowImage(isShowImage => !isShowImage);
  };

  return (
    <div>
      { isShowImage && <div className={"options"}>
         <img src={'https://image.shutterstock.com/image-photo/silhouette-boy-playing-cricket-evening-600w-1605103354.jpg'} alt={"teleconsultation"} />
      </div>}
      <br />
       <button onClick={imageShowHandler}>Toggle Image</button>
    </div>
  );
};


ReactDOM.render(<Parent />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Minimal code

Define a default image in a state and update it based on some condition.

const [defaultImage, setDefaultImage] = useState<image> // your image 

useEffect(() =>{
    if(someCondition) {
        setDefaultImage('newImage');
    }
}, [])


{
    <div className={"options"}>
        <img src={defaultImage} alt={"teleconsultation"}/>
    </div>
}      

This way in future if you intend to display images mulitple times no if/else would be needed at all places. Same code would work too.

  • Related