Learn how to apply inline styles to multiple objects within a single element using React

In my project using React, I am attempting to apply styles only to a specific element within another element. Here is an example with an h1 tag:

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>
    )
}

I've been trying different methods to target styling specifically to the 'timeOfDay' text only, but it seems that the style={} attribute affects the entire element. Does anyone have suggestions on how to achieve this? Thank you in advance!

Answer №1

Wrap the timeOfDay with a span element and apply styling to it

<div>
      <h1 className="navbar"><span style={styles}>{timeOfDay}</span> {`${firstName} ${lastName}`} The current time is {hours} o'clock</h1>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The pictures in a <div> tag are not showing up

Functionality: I have set up 2 different <div> elements with unique IDs. Each of these <div> elements will make an ajax call to fetch a specific set of images for display. To summarize, both <div> elements are invoking the same ajax met ...

What is the best way to set up a server-sent-events broadcast feature in totaljs?

Let's imagine this situation: Client1 and Client2 are currently in session1 Meanwhile, Client3 and Client4 are part of session2 My aim now is to send event "a" to all clients in session1 exclusively. I came across this example: https://github ...

Utilize React to dynamically load diverse data arrays into a slick slider component

I am currently working on a component that includes a slider displaying photos linked to different rooms. The next step is to move this slider to a separate page or component, which will display content for rooms, news, and promotions using different arr ...

What steps can be taken to stop Express from displaying a "502 Bad Gateway" error when failing to respond to a request?

In a unique scenario where I am working with an express 4 server and need to prevent a client from responding to a request that does not respond to a 503 status code, I am facing some challenges. When I simply do not send a result, Express automatically s ...

Creating a button that integrates an image within a single div element

Currently, I understand the code: $('#leftDev').css("background-image", "url(img/1.png) "); will set the entire background of my leftDiv to display "1.png". However, I would like to position this image as a regular picture within the div and no ...

Using Redux store data to dynamically fill a Material-UI dropdown menu

I am attempting to automate the population of my Redux store fields with a method I imported. Is my current approach the correct way to achieve this? Do I need to create mapping options for each field? Each of my dropdowns contains a PopulateDropdown list ...

Unable to trigger enzyme test click event on a material ui Checkbox within a redux-form Field component

I am currently working on setting up an enzyme/mocha/chai test to replicate the scenario where the state of a materialUI Checkbox component changes from true to false. The Checkbox is enclosed within a redux-form Field, and I am facing difficulties in simu ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

How can we determine the number of duplicate elements in an array?

Is there a way to tally the occurrences of specific words from a list within a given set of phrases and store the count in designated variables? let counter = []; let wordToCount = ["tomato","cat"]; let phrasesToCheck = ['my cat like potatoes', ...

Heroku refreshes my JSON document

My node.js app relies on a basic JSON file as the model. To keep things simple since it's only an MVP with minimal data storage requirements, I opted not to set up and configure a MongoDB database. Instead, I just read from and write to a JSON file lo ...

Microservice for Logging Middleware

As part of our transition to a microservices architecture, I need to save logs into a MySQL database for each request and response. Currently, the backend, built with NodeJS and Express, has a middleware that handles this task for each microservice individ ...

Troubleshooting problems with resizing images using CSS

I am experiencing an issue with resizing images that I have configured in the admin panel. .users-list>li img { border-radius: 50%; max-width: 100%;    height: auto;     width: 100px;     height: 100px; } When enlarged, the images l ...

text within the table is overlapping when being created dynamically in the <table> using javascript and jquery.quickflip.js

Hello everyone, I am currently working on dynamically generating a table using tabs created with jquery.quickflip.js. However, I have run into an issue where the text from one tab may overwrite values in another tab when switching between them. Below is ...

Verify JSON Web Tokens (JWT) with Node.js using Auth0

I have obtained a JWT from Auth0 and successfully decoded it using the middleware function on my Node server (utilizing https://www.npmjs.com/package/jwt-node) function authoriseToken(req, res, next) { const token = req.headers.authorization.replace(&ap ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

I experienced issues with the brackets software freezing up while using the Bootstrap min CSS file

Recently, I've been using brackets as my text editor and have run into an issue with the bootstrap.min CSS file. For some reason, it keeps freezing whenever I try to load it in brackets. Oddly enough, HTML files work perfectly fine, but ...

Issue with Material-ui 4.9.5: 'required' attribute malfunctioning for TextFields

I am experiencing an issue with a simple TextField that has the 'required' attribute. When inspecting the HTML, I noticed that it generated 'required=""' in the 'input' element, which is preventing the required error message f ...

The try/catch block in Node continues to propagate upwards

I'm struggling to capture errors during server-side rendering, especially since they reach the catch block but still cause an uncaught exception leading to a crash. Below is a simplified version of the function causing the issue: export default (htm ...

Provide net.socket as a parameter

What is the best way to pass the net.socket class as an argument in this scenario? Here's my code snippet: this.server = net.createServer(this.onAccept.bind(this)); this.server.listen(this.port); } Server.prototype.onAccept = function () { // Ho ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...