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

Populate an ASP Form using Javascript in Android Studio

Being relatively new to Android studio, I have been experimenting with various methods but now need some assistance. I am looking to input data into an ASP.NET Website-form using Android studio. The traditional JavaScript approach does not seem to be effec ...

There appears to be a slight issue with the tailwind dark mode not fully extending when scrolling to the bottom of the page

While using dark mode in a Next.js web app with Tailwind, you may have noticed that when scrolling, if you go past the scroll container (almost as if you're bouncing off the bottom or top of the page), the dark mode doesn't extend all the way. In ...

Learning about the intricacies of backend Node.js through Angular using GET requests

I am having trouble retrieving the query parameters from a frontend GET request on the backend side. I have attempted to use url and query, but still need assistance fetching the query on the nodejs side. Can someone recommend a method that would allow me ...

The field "addWorkout" cannot be queried on the type "Mutation"

My journey with GraphQL has just begun, and after resolving a reference error in my previous question, I have encountered a new challenge. It appears that adding a workout is not working as expected, as the schema does not recognize it as a mutation field. ...

The error message received when attempting to install Copay using npm is: unable to execute in working directory %s %s (working directory

While attempting to install copay bitcopay, I ran into an error when executing sudo npm install. $ sudo npm install Password: npm WARN lifecycle <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e7d716e7f675e2c3029302e">[emai ...

Customize CSS styles based on Angular material stepper orientation

Is it possible to change the CSS style of an angular material stepper based on its orientation? For instance, can we set a red background when the stepper is displayed vertically and a blue background when horizontal? ...

Angular components are not properly adhering to the specified height and width dimensions for child elements

I seem to be having trouble applying height/width to a child component in angular. Can someone take a look and point out where I may have gone wrong? app.component.html <app-child [width]="10" [height]="10"></app-child> .child.ts import { C ...

count how many times a value appears in an array within MongoDB

I have a dataset structured like this: { "_id" : ObjectId("5a1414430b4215041c768f50"), "slug" : [ "a", "b", "c" ] }, { "_id" : ObjectId("5a1414430b4215041c768f51"), "slug" : [ "a", "d", "e" ] }, { "_id" : ObjectId( ...

Obtaining page information from a frame script in e10s-enabled Firefox: A guide

One of the challenges I'm facing is with my Firefox extension, where a function loads page information using the following code: var title = content.document.title; var url = content.document.location.href; However, with the implementation of multi- ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...

There seems to be a problem retrieving the JSON file

My JavaScript file is designed to fetch a JSON file and execute a function if successful. If there's an error, it should display an alert window with the message "error". However, despite checking the syntax, I keep receiving an error alert every time ...

Guide to establishing a connection between Reactivesearch and an external Elasticsearch cluster

Trying to link my reactive search app with an external Elasticsearch provider (not AWS) has been a challenge. The provider does not allow any modifications to the Elasticsearch cluster or the use of Nginx in front of it. In accordance with the reactive se ...

Having difficulty bringing in personalized fonts

I've recently created a nextjs app and I'm encountering an issue - I can't seem to import custom fonts. I attempted adding ttg files and using @fontface, but the fonts aren't displaying correctly. Can someone please assist me? Below is ...

What should be done if an image is not wide enough to stretch it to match the width of the window?

When the image is not full screen, it looks fine but when it's viewed in full screen, there's a white area on the right side which is likely due to the image not being large enough. Is there a way to automatically stretch the image so that its wi ...

Tips for positioning an MUI element inside a container to extend to the edge of the browser window

Currently, I'm working on a project with a Material-UI (MUI) container that contains a Stack element. Within this Stack, there are two Box elements displayed in a row, each set to take up 50% of the width. In my design, I want the second box to break ...

Error: Unable to execute this.context.router.push due to it not being a function

I recently encountered an issue where the browser console displayed the same message as the post title. The problem occurred when trying to navigate to a profile page after clicking a dropdown button. contextTypes: { router: React.PropTypes.func }, _h ...

Ensure that Colorbox remains centrally positioned even while scrolling

I have noticed a difference in behavior between thickbox and colorbox when it comes to scrolling. Thickbox always stays centered on the screen even when the user scrolls vertically, while colorbox fades out and leaves just a grayed background. Is there a w ...

Create a sleek Bootstrap 4 webpage featuring a fixed footer and navigation bar. However, the challenge lies in ensuring that the content fills the

Currently, I am in the process of creating a template page that includes a navbar and a footer with the intention of adding additional columns within the main div (container-fluid) at a later stage. However, I have encountered two issues that I cannot seem ...

How can you reach a constant from a different component in React?

I am new to developing a react application and struggling with accessing const data from another component. The specific constant I need access to is located in the TableComponent.js file. TableComponent.js export default function({ infinite }) { const [ ...

Deciphering the difference between a null object and the numeral 0

While working on Codewars and attempting to solve a problem, I encountered an interesting question. The task was to create a "toDense()" function that takes a sparse array as input and returns the corresponding dense array. An example test case provided w ...