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

I encounter issues when trying to run "yarn start" following the integration of tailwindcss into my React project

I'm encountering an issue while integrating tailwindcss with postcss into my React Application (built using create-react-app). To address this, I modified the scripts section in my package.json. Here is how my updated package.json appears: { "name ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

Ways to implement distinct values for model and input field in Angular 5

I'm currently working on an Angular 5 application and I have a requirement to format an input field with thousand separators (spaces). However, the model I am using only allows numbers without spaces. Since my application is already fully developed, ...

PyQt TreeView scrollbar obstructing the header

I've been experimenting with the QTreeView widget (instead of QListView) in order to have a horizontal header. Additionally, I wanted to use stylesheets to customize the colors and appearance of the header and scrollbars. However, there is an issue w ...

Is it possible to configure the Eclipse Javascript formatter to comply with JSLint standards?

I'm having trouble setting up the Eclipse Javascript formatting options to avoid generating markup that JSLint complains about, particularly with whitespace settings when the "tolerate sloppy whitespace" option is not enabled on JSLint. Is it possible ...

When the jquery loop fails to function

I need to dynamically add a class to a specific tag using jQuery depending on an if condition. Here's the code snippet: if ($(".asp:contains('Home')")) { $("ul.nav-pills a:contains('Home')"). parent().addClass('active ...

Tips for keeping the app on the same route or page even after a refresh

I'm currently diving into the world of React and am in the process of constructing a CRUD application. I've successfully created multiple pages that utilize react-router-dom for navigation with authentication. The pages are accessible only to log ...

Leveraging Vue.js to showcase API information through attribute binding

My application is designed to allow a user to select a Person, and then Vue makes an API call for that user's posts. Each post has its own set of comments sourced from here. You can view the codepen here Here is my HTML structure: <script src="h ...

Determine whether the response originates from Express or Fastify

Is there a method to identify whether the "res" object in NodeJS, built with Javascript, corresponds to an Express or Fastify response? ...

Trouble getting proper alignment displayed with JavaScript and CSS

If anyone has a solution for printing content in a div using JavaScript and CSS, please help. The main div with the id 'preview' contains content taken from a database using PHP and MySQL. However, the data on the print page appears vertically an ...

Require help with personalizing a jQuery horizontal menu

I recently downloaded this amazing menu for my first website project By clicking the download source link, you can access the code Now, I need your kind help with two issues: Issue 1: The menu seems to be getting hidden under other elements on the page ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

The store couldn't be located by React-Redux

Working with React, Redux, and Express is causing issues for me. Every time I refresh localhost/courses, an error regarding 'store' not being found pops up. However, If I navigate from localhost -> click to nav course, everything works smoothl ...

Ensuring user remains authenticated with Firebase authentication in a ReactJS application

I am facing an issue with my react app that utilizes Firebase for authentication and other tools. Specifically, on a certain page, I am checking if the user is logged in using firebase.auth().currentUser;. I have also attempted to use firebase.auth().onAut ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

ng-include failing to retrieve file name containing UTF-8 character

I encountered an issue with the ng-include directive in the code snippet below. The file name it's trying to access contains a special character, specifically an ñ, resulting in a not found error being displayed. <div ng-include="'{{mainCtrl ...

Utilizing Express JS to Optimize JPEG File Loading with Cache Headers

I have been working on implementing Cache-Control for my static image files. I have successfully set this header for HTML and JS files: https://i.stack.imgur.com/9VuWl.png However, I am facing challenges with JPEG files: https://i.stack.imgur.com/p52jm. ...

Center align the label and textbox using CSS in a horizontal arrangement

Is there a way to center the label text within the div? My desired outcome is: ----------- Name: | textbox | ----------- For a demo, check out this code: http://jsfiddle.net/53ALd/2053/ ...