The worm The worm - 1 month ago 18
React JSX Question

Styling an objects property using React

How do I change the style of a react component?
This will error on the background color but when removed it will output 'hello'
I want to style based on property in an object in react.

if(this.state.msg[0].msg.author.name == 'Rich){
background-color: red;
console.log('hello')
};

Answer

In React we use camelCase when specifying the desired CSS style names.

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name https://facebook.github.io/react/tips/inline-styles.html

Here is a demo of how you could conditionally apply styles depending on the values kept in the state: http://codepen.io/PiotrBerebecki/pen/xEyqER

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      msg: [
        {msg: {author: {name: 'Rich'}}},
        {msg: {author: {name: 'John'}}},
        {msg: {author: {name: 'Pete'}}}
      ]
    };
  }

  render() {

    const style1 = {
      backgroundColor: 'red'
    };

    const style2 = {
      backgroundColor: 'blue'
    };

    const style3 = {
      backgroundColor: 'gray'
    };

    const getStyleName = (name) => {
      switch (name) {
        case 'Rich':
          return style1;
        case 'John':
          return style2;
        default:
          return style3;
      }
    };

    const renderNames = this.state.msg.map((item, index) => {
      return (
        <p key={index} style={getStyleName(item.msg.author.name)}>
          {item.msg.author.name}
        </p>
      );
    })

    return (
      <div>
        <h1>React</h1>
        {renderNames}
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);