Categories

Friday, October 4, 2024
#919814419350 therichposts@gmail.com
Reactjs

Reactjs dynamically added class to html elements

Reactjs dynamically added class to html elements

Hello, welcome to therichpost.com. In this post, I will tell you, Reactjs dynamically added class to html elements. Reactjs is a Javascript Library to build user interface

In this post, I am adding className property  to li based on object value and this is very interesting and I am doing it first time.

reactjs-dynamic-add-classname

I will add the class Name with the help of ternary operator and here is the working code and you need to add this into your index.js file:
import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component{
  constructor()
  {
    super();
    //declare custom data array of object
    this.state = {
      tasks:[
      {name:'lession1', completeed:true},{name:'lession2', completeed:false}
      ]
    }
  }
  render()
  {
    return (
      <ul>
      {
        //map array data
        this.state.tasks.map(function(task){
                                          //adding class name dynamically based in task completed value true or false
            return <li className={task.completeed ? 'green' : 'red'} key={task.name}>{task.name}</li>
        })
      }
      </ul>
    )
  }
}

ReactDOM.render(<Hello />, document.getElementById('root'));

 If you have any query related to this post then please do ask in below comment section and I will come with more post related to reactjs.

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.