Sachin Jain
Sachin Jain

Reputation: 21842

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 ?

Upvotes: 9

Views: 33841

Answers (5)

Pradip Rupareliya
Pradip Rupareliya

Reputation: 574

Write in code

className={`form-control-sm d-inline per_player ${"per_player_b_" + index + "_score"}`}

and You will get

enter image description here

Upvotes: 0

Vlad Bezden
Vlad Bezden

Reputation: 89527

You can use JavaScript template literals

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

Your code can be written in following way:

const Alert = ({type, message}) =>
    <div className={`alert ${type}`}>{message}</div>

Upvotes: 0

Sachin Jain
Sachin Jain

Reputation: 21842

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.

Upvotes: 8

David L. Walsh
David L. Walsh

Reputation: 24818

Take a look at the classnames package. You can do stuff like this:

className={classNames('alert', `alert-${type}`)}

or

className={classNames({
    'alert': true,
    'alert-success': success,
    'alert-error': error
})

Upvotes: 4

Nick Zuber
Nick Zuber

Reputation: 5637

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>
  }
});

Upvotes: 4

Related Questions