Home > Software design >  How to conditionally set a Style variable in JSX (React)?
How to conditionally set a Style variable in JSX (React)?

Time:02-13

I am trying to conditonally set the border color of an image. Depending on the image name, I would like to set a different border color.

Here is my code:

<div className="row">
    {asideData.imageGallery2.map( (img, i) => {
        return(
              <div className="col-md-6 col-lg-4">
                   // if img.name includes "Quartz" then make border color red
                   // if img.name includes "Flake" then make border color blue
                  <img src={img.img} alt="" key={img.name} style={{border:"5px solid #555"}}/>
               </div>) 
               })}
               
</div>

CodePudding user response:

Use a template literal in the string for the border property so you can use the conditional operator to alternate between the two possibilities.

Define the border in a separate variable beforehand so that it's not unreadable.

You aren't using the index parameter, so feel free to remove it.

asideData.imageGallery2.map((img) => {
    const border = `5px solid ${
        img.name.includes('Quartz')
        ? 'red'
        : img.name.includes('Flake')
            ? 'blue'
            : 'black' // default color
    }`;
    return (
        <div className="col-md-6 col-lg-4">
            <img src={img.img} alt="" key={img.name} style={{ border }} />
        </div>)
})

CodePudding user response:

try

style={{border:"5px solid", borderColor: img.name.includes('Quartz') ? 'red' : (img.name.includes('Flake') ? 'blue' : null)}}/>

Check if that works

  • Related