Displaying the age figure in JSX code with a red and bold formatting

I have a webpage with a button labeled "Increase Age". Every time this button is clicked, the person's age increases. How can I ensure that once the age surpasses 10, it is displayed in bold text on a red background? This should be implemented below the "Change" and "Change Age" buttons.

The current age is:

I believe I need to incorporate conditional rendering in JSX using the changeBackground function, but I'm not entirely sure how to proceed. Here is my current code snippet:

import React from 'react';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.changeClicked = this.changeClicked.bind(this);

        this.state = {
            name: 'jerry',
            age: 10
        }
    }

    changeClicked() {
        this.setState({name: 'Anne'});
    }

    changeAge() {
        //this.setState({age : this.state.age + 1, name : 'Jacob'})
        this.setState((prevState) => ({age: prevState.age + 1}));
        console.log("The age is " + this.state.age);
        //this.setState({name : 'Maureen'})
    }

    changeBackground() {
        this.setState({backgroundColor: 'red'});
    }

    render() {
        const age = this.state.age;
        const color = 'white';

        return (
            <div>
                {
                    <p style={{color: 'red'}}>name and age information</p>
                }
                <h3 style={{backgroundColor: color}}>Name is {this.state.name} and age = {age}</h3>
                <button onClick={this.changeClicked}>Change</button>
                <button onClick={() => this.changeAge()}>Change Age</button>
                <p>Current Age: {age}</p>
                <div></div>
                <Info nimi={this.state.name} address="Europe" />
            </div>
        )
    }
}

export default App;

Answer №1

To add style to an element based on certain conditions, you can create a CSS class and then apply that class when the conditions are met. Here's an example:

.price-over-50{
color:blue;
font-weight:bold;
}

Then in your code:

<span className={`${this.state.price > 50 ? "price-over-50" : ""}`}>Price is: {price}</span>

Answer №2

Hey there, I created this especially for you on CodeSandbox. Feel free to copy and use it!

To enhance the styling, just add a CSS class like this:

.red {background-color: red;}

And in your code, incorporate it like so:

render() {
  const age = this.state.age;
  let classes = "";
  classes += this.state.age > 10 ? "red" : "";

  return (
    <div>
      {<p style={{ color: "red" }}>Name and Age Information</p>}
      <h3 className={classes}>
        Name is {this.state.name} and age = {age}
      </h3>
      <button onClick={this.changeClicked}>Change</button>
      <button onClick={() => this.changeAge()}>Change Age</button>
      <p>Age: {age}</p>
    </div>
  );
}

}

Answer №3

Give this code snippet a try {this.state.colorbackground === true ?

 import React from 'react';

class App extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            name : 'jerry',
            age : 10,
            colorbackground: false
        }
    }


    changeClicked = () => {
      this.setState({nimi : 'Anne'});
    }

    changeAge = () => {
        this.setState((prevStatus) => ({age : prevStatus.age + 1}));
        console.log("Age is " + this.state.age);
        if(this.state.age >= 10) {
          this.setState({
              colorbackground: true
          })
        }
    }

    render()
    {
        const age = this.state.age;
        const color = 'white';

        return (
            <div>
                {
                <p style={{color : 'red'}}>name and age information</p>
                }
                <h3 style={{backgroundColor : color}}>Name is {this.state.name} and age = {age}</h3>
                <button onClick={this.changeClicked}>Change</button>
                <button onClick={() => this.changeAge()}>Change age</button>
               {this.state.coloredbackground === true ?
             <div style={{color: 'blue', background: 'red'}}>Age is: <span style={{fontWeight: 'bold'}}>{age}</span></div> :
              <p>Age is: {age}</p> }
                <div>
      </div>
                <Info nimi={this.state.name} address="Europe" />
            </div>
        )
    }
}

export default App;

Answer №4

For example:

<p>If the age is over 10, it will be displayed in red: {age > 10 ? (<b style={{color : 'red'}}>{age}</b>) : {age}}</p>

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

Top method for changing Enum to Set in TypeScript

Take a look at the enum below: enum Animes { OnePiece = 'One Piece', Naruto = 'Naruto', Bleach = 'Bleach' } How can we efficiently transform this enum into a Set? ...

What steps can I take to transform this jquery code into a react.js equivalent?

Can someone help me convert this jQuery code into ReactJS? I've been trying, but encountering a lot of errors. I'm new to jQuery and having trouble understanding it. In simple terms, this is how the code works: When I click on the text "Laptop, ...

What is the best way to create a border of white space around the background color of a table cell using CSS?

Is there a way to create a white space around the background color of a table cell using CSS? My current code has the background color extend all the way to the edge, and padding only affects the content, not the background color. #main-monitor { widt ...

What is the best way to fix the lint check error within a Vue file's styling?

https://i.sstatic.net/PPA88.jpg Is there a way to eliminate the red wavy lines on the screen? ...

What is the method used by Vue.js to establish observers in computed properties?

Consider this scenario: computed: { greeting() { const state = this.$store.state; if (state.name === 'Joe') { return 'Hey, Joe'; } else { return 'Hello, ' + state.name; } } } Which object(s) w ...

Exploring JSON data in JavaScript

In my Json data, I have a nested structure of folders and files. My goal is to determine the number of files in a specific folder and its sub-folders based on the folder's ID. Below is an example of the JSON dataset: var jsonStr = { "hierarchy": ...

Changing the background color of MUI TextField for autocomplete suggestions

I am currently facing an issue with the background color of auto-complete fields in my React.js and Material UI app. The auto-complete fields are adding a white background which is unnecessary. Interestingly, when I manually add text, this issue does not ...

Utilize the hexadecimal color code as a string within the darken function

When working with a less style, I have a string variable. @colorString: 'DADADA'; I can convert it into a color: @color: ~'#@{colorString}'; Then, I am able to use @color to define a value in a style: div { color: @color } However ...

The function maybeStripe.apply is not defined

Greetings, Encountering a Stripe error in Gatsby upon page load Error: Uncaught (in promise) TypeError: maybeStripe.apply is not a function import React, { useEffect, useState } from 'react'; import { loadStripe } from '@stripe/str ...

Is it more beneficial to include a JSON or CSV file in a web application in order to store default data?

In the process of developing a React web application, I am enabling users to select from a predefined list of data in order to generate a version that they can modify as needed. At present, the data is stored in an excel file. My initial plan was to conve ...

Attempting to implement scroll-based animation on my webpage

Having trouble integrating this animation (from codepen) into my website. It works fine on its own, but when I try to add it to my site, it doesn't show up. I want it to appear in the middle at the bottom of the background image. Check out the codepe ...

Tips for positioning your side navigation menu parallel to the page edge

Im looking to have the side navigation floated to the left as I scroll down the page. I tried using the sticky property, but it didn't work out. Here's a snippet of the code: .sticky-class { position: sticky; top: 30px; } This is how my HTML ...

What is the functionality of require(../) in node.js?

When encountering var foo=require(../), what specific modules does node.js search for? It may appear to look in the directory above the current one, but what exactly is it seeking and how does it function? Is there a comparison with include in C or impor ...

Customize bullet list icons to adjust in size based on content using css

In my CMS project, the CMS team has a special requirement regarding unordered and ordered lists. They want the size of the bullet list icon to adjust according to the text content within the list. The image below shows the default design of a list item: ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

Struggling to launch my inaugural React project on my local machine - encountering issues with getting npm start to

Whenever I attempt to run npm start, I encounter the following error message: [Error: ENOENT: no such file or directory, open 'C:\Users\Elijah\vscode\React project\react-project\.next\BUILD_ID'] { errno: -4058 ...

Fetching a Wikipedia page using AJAX or the fetch() method

I am currently attempting to dynamically retrieve a Wikipedia webpage within the browser in order to utilize XSLTProcessor for further processing of the XHTML content. Unfortunately, my efforts have been unsuccessful as Wikipedia is not sending the necess ...

React - Exploring the depths of functional components

Picture this: a straightforward form that showcases several unique components with customized layouts. The custom components include: <UsernameInput />, <PasswordInput />, <DateTimePicker />, <FancyButton />, <Checkbox /> Th ...

Display information retrieved from Firebase Firestore within a React component

Recently, I delved into the world of Firebase Firestore DB to render data in my app. Initially, a tutorial guided me through the process, but now as I attempt to fetch data from my own database, I find myself facing new challenges. Below is the code block ...

I am having trouble retrieving the content-length from the response headers within the app.use() middleware function

Can anyone help with retrieving the content-length from response headers within the app.use() middleware function? const app = express(); app.use((req, res, next) => { // Need to find a way to access content-length of res console.log("co ...