0

In React i'm trying to apply style only to one object inside of an element like h1 here is an example

const Header = () => {

  const firstName = "Ashraf";
  const lastName = "Fathi";
  const date = new Date();
  const hours = date.getHours();

  let timeOfDay;
  const styles = {
    color: ""
  }
  if (hours < 12) {
    timeOfDay = "Good morning"
    styles.color = "#ff474d"
  }
  else if (hours >= 12 && hours < 17) {
    timeOfDay = "Good afternoon"
    styles.color = "#7b5dff"
  }
  else {
    timeOfDay = "Good night"
    styles.color = "#01ff41"
  }
  return(
    <div>
          <h1 className="navbar" style={styles}>{timeOfDay} {`${firstName} ${lastName}`} It is currently {hours} clock</h1>
    </div>
    )
}

what i'm trying to do is to apply style to only timeOfDay so how could i achieve that? i have tried different approaches but it all comes down to style={} affecting the whole element which is not looking for. Thanks in advance

1 Answer 1

1

Add a span around timeOfDay and then pass style to it

 <div>
      <h1 className="navbar"><span style={styles}>{timeOfDay}</span> {`${firstName} ${lastName}`} It is currently {hours} clock</h1>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.