can this.props be used to style the div tag?

566 Views Asked by At

I would want to use the this.props data in the div tag. i have the color in the data which i would want to set dynamically . Would it be possible to use this.props in the div tag?

var cont =  {
      height: "90px",
  width: "20%",
  background: "LightBlue",
  display: "inline-block",
  padding: "5px",
      margin: "5px"
};

var Comment = React.createClass({    
    render: function () {
      return (
          <div style={cont}>
              <span>
                  {this.props.author}
                  {this.props.col}
              </span> 
          </div>   
      );
    }
});
2

There are 2 best solutions below

1
On

Try this:

<div style={{backgroundColor: this.props.col}}>

Offical React style documentation

1
On

Look:

var Comment = React.createClass({
    render: function() {
        return (
            <div style={{backgroundColor: this.props.col}}>
                <span>
                    {this.props.author}
                    {this.props.col}
                </span>
            </div>
        );
    }
});

this.props.color here is a prop of Comment component and not of the div. You can use this prop wherever you want in this component.

As @MayankShukla said, for updating field in style object you can use Object.assign.