Conditional image src render react

Viewed 6480

I am building a resusable react component to display some custom message with either warning icon or success Icon.

I will pass the the warning or success prop down so as when a user wants to use the component he either sends warning or success.

this is the code so far

<img
        style={{ width: '48px', height: '48px', position: 'absolute' }}
        src={warningIcon}
      ></img>

how can i conditionally either put {warningIcon} or {successIcon} when i do create the prop and send down to the child component?

2 Answers

Pass a boolean prop for success/warning and use a ternary operator to conditionally set the src attribute.

Something like:

const Img = ({ success }) => (
  <img
    style={{ width: '48px', height: '48px', position: 'absolute' }}
    src={success ? successIcon  : warningIcon}
  />
);

Use a ternari in the source:

   const [ stateImage, setStateImage ] =useState(false);

      src={stateImage ? 'one image' : 'another image'}
Related