Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline-styles in ReactJS

I'm new to ReactJS. I was trying to change simultaneously the text and the colour of a button when clicking on it. This code works:

class ToggleHelp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isHelpOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isHelpOn: !prevState.isHelpOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
      </button>
    );
  }
}

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

But when I try to aplly an inline style like the following, code stops working.

<button style={background:yellow} onClick={this.handleClick}>
  {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>

I've tried several times, doing it in various ways. I'd like it to be an inline style for the moment. Is it possible to apply inline styles directly from React? If yes, the idea is to evaluate the status and set one color on another via conditional statement.

like image 705
Esti Avatar asked Jul 26 '17 17:07

Esti


People also ask

Can We Use inline CSS in React?

The official React documentation frowns upon the use of inline styling as a primary means of styling projects and recommends the use of the className attribute instead.

What is inline in React?

What is an inline function? Simply put, an inline function is a function that is defined and passed down inside the render method of a React component. Let's understand this with a basic example of what an inline function might look like in a React application: export default class CounterApp extends React.

What is inline style with example?

Inline CSS: Inline CSS contains the CSS property in the body section attached with element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute. Example: html.


1 Answers

Declare your inline style as an object:

<button style={{ background: 'yellow' }} onClick={this.handleClick}>
  {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>
like image 78
Danny Delott Avatar answered Oct 10 '22 07:10

Danny Delott