Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide dynamic className to element in React Class render method

I have a ReactClass with name Alert. Its render method returns a div with class alert alert-success or alert alert-error according to the type passed while creating element. I just want to know how to add class based on the type of alert element.

Here is my attempt:

var Alert = ReactClass({
  render: function() {
    return <div className="alert {this.props.type}">{this.props.message}</div>
  }
});

var successAlert = React.createElement(Alert, {
  type: 'alert-success'
  message: 'Information saved successfully!!'
});

When JSX Template is compiled this.props.type is not converted to the class passed to element. How to achieve this ?

like image 928
Sachin Avatar asked Mar 04 '16 02:03

Sachin


People also ask

How do you apply dynamic class to an element?

In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.


2 Answers

Looks like I have found answer to my question. We can simply do something like this:

var Alert = ReactClass({
  render: function() {
    return <div className={"alert " + this.props.type}>{this.props.message}</div>
  }
});

Just put your classes inside Template evaluators { } in this case. Create your class string based on your props and states.

Hope this is helpful to others.

like image 192
Sachin Avatar answered Oct 03 '22 15:10

Sachin


One way to accomplish this is to have a string which will contain all of your classes and then set it to the Component's className:

var Alert = ReactClass({

  var yourClassName = 'alert ';

  // Add any additional class names
  yourClassName += this.props.type + ' ';

  render: function() {
    return <div className={yourClassName}>{this.props.message}</div>
  }
});

or alternatively you can store your class names in an array and convert it to a class friendly string when you're ready to use it:

var Alert = ReactClass({

  var yourClassArray = [];

  // Add any additional class names
  yourClassArray.push('alert');
  yourClassArray.push(this.props.type);

  var classString = yourClassArray.join(' ');

  render: function() {
    return <div className={classString}>{this.props.message}</div>
  }
});
like image 24
Nick Zuber Avatar answered Oct 03 '22 15:10

Nick Zuber