How to use Config Objects in components in React.js?

What is a Lifecycle Method in React.js? »

If you look at the code you’ve written inside DayNightDisplay.js, there should be a way to combine the text “It’s day!” with the image “day.png” and the text “It’s night” with “night.png”.

This is a very appropriate situation to learn about Config Objects in Javascript.

Right after the import statements, write down the following configuration object in DayNightDisplay.js:

const dayConfig = {

    day: {
       text: "It's day",
       image: "day.png"

    night: {
       text: "It's night",
       image: "night.png"


Next up, inside the getDay() function, make the following changes:

const getDay = hours => {

    // determine whether it's day or night

    // based on hours group

    if (hours >= 7 && hours <= 17 ){
    } else {
    return dayConfig.night.text;


To access the value of day text, you’re using Similarly for image path, you’re using With this, you’re able to group the similar objects in a better way.

This also helps you to get dynamically generated value and assign it to static variables. Let’s say the value of myValue can either be “day” or “night”. And if you use dayConfig[myValue], you’ll get a set of day values (both text and image) or night values (both text and image). You can further store them in separate variables like this:

const { newText, newImage } = dayConfig[myValue];

And in the DayNightDisplay functional component, make the following changes:

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 ===
           imageURL =;
           imageURL = dayConfig.night.image;

    // console out rightNow value

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



Save the files, and everything should work just fine.

Leave a Comment