Home > Mobile >  React: condition based on url (image)
React: condition based on url (image)

Time:06-09

I have 2 pictures, and I want to make a condition if he is a man bring him this picture and if he is a woman bring him the second picture and if he is different from the two then he will not present anything

import Female from '../images/Me.png';
import male from '../images/Daniel.png';

style={{backgroundImage:props.gender === 'Male' ? `url(${male})`: 
null,backgroundImage:props.gender === 'Female' ? `url(${Female})`: null }}

I understand because I gave null so he overrides it and it will not show me the Male in life but I did not find another way how to realize it

CodePudding user response:

You can write this way:

style={{backgroundImage: !!props.gender ? (props.gender === 'Male' ? `url(${male})`: 
`url(${Female})`) : null }}

If props.gender is truthy then check male or not? If gender not specified(falsy) then it will be null.

The other way you can do it by stricting the value yourself.

style={{backgroundImage: ["Male","Female"].includes(props.gender) ? (props.gender === 'Male' ? `url(${male})`: 
    `url(${Female})`) : null }}

This will check the value of props.gender is either male or female first otherwise it will be null.

  • Related