Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional image src render react

Tags:

reactjs

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?

like image 941
SImon Haddad Avatar asked Apr 27 '26 09:04

SImon Haddad


1 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}
  />
);
like image 169
Drew Reese Avatar answered Apr 28 '26 23:04

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!