How to display conditional images in a component in React.js?

What is a Lifecycle Method in React.js? »

You’ve already found a way to find out whether it’s day or night in a React.js component. Next, you need to write some logic to display graphics or images as per the result (day or night).

You’re going to use a variable and store the image URL inside it. You’ll rename the image names accordingly, so that it matches with the given URL. You’re going to generate the image URL value based on whether it’s day or night from a pre-existing variable called rightNow.

Let’s create a new variable called imageURL and store a blank value in it (inside the DayNightDisplay component):

let imageURL = “”;

Next, you need to get the imageURL as per your conditions said above:

    if (rightNow === "It's day")
           imageURL = "day.png";
    else
           imageURL = "night.png";

Next, modify the return statement as follows:

    return <div>
       <div>
           <img alt="Day Night" src={imageURL}/>
       </div>

       <div>
           {rightNow}
       </div>
    </div>;

Next up, you need to find some images (from Google or some loyalty-free image sites) for “day icon” and “night icon”. For instance, I’ve saved these two images and renamed them to day.png and night.png inside the public directory:

night icon    day icon

 

Save the file after the whole file (DayNightDisplay.js) looks like:

import React from 'react';

const getDay = hours => {

    // determine whether it's day or night
    // based on hours group

    if (hours >= 7 && hours <= 17 ){
       return "It's day";
    } else {
       return "It's night!";
    }

}

const DayNightDisplay = props => {

    // convert hours from string to integer

    const hours = parseInt(props.hours, 10);

    // store the returned value in rightNow

    const rightNow = getDay(hours);

    let imageURL = "";

    // get proper image

    if (rightNow === "It's day")

           imageURL = "day.png";

    else

           imageURL = "night.png";

    // console out rightNow value

    console.log(rightNow);

    return <div>
       <div>
           <img alt="Day Night" src={imageURL}/>
       </div>

       <div>
           {rightNow}
       </div>

    </div>;
};

export default DayNightDisplay;

Inside the return statement, you’d notice that you’ve used an img tag. At src={imageURL}, you’re basically providing the image file name that’ll be rendered just before the rightNow value. Since the imageURL is dynamic and it’ll either be night.png or day.png (which is calculated above), you’re using the JSX syntax to get the value of imageURL and not hardcoding any value.

Save the file, restart the server and you should immediately see the changes!

Leave a Comment