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.
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 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.
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.
Declare your inline style as an object:
<button style={{ background: 'yellow' }} onClick={this.handleClick}>
{this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With