React change button color onclick code example
Example 1: change style on click react
Html
<div id="app"></div>
Css
button{
width: 80px;
height: 40px;
margin: 15px;
}
.blackButton{
background-color: black;
color: white;
}
.whiteButton{
background-color: white;
color: black;
}
React
class Test extends React.Component {
constructor(){
super();
this.state = {
black: true
}
}
changeColor(){
this.setState({black: !this.state.black})
}
render(){
let btn_class = this.state.black ? "blackButton" : "whiteButton";
return (
<div>
<button className={btn_class}
onClick={this.changeColor.bind(this)}>
Button
</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.querySelector("#app"))
Example 2: react change button color
The react Button component renders the native button on each platform it uses. Because of this, it does not respond to the style prop. It has its own set of props.
The correct way to use it would have been
<Button color="#ff5c5c" title="I'm a button!" />
You can see the documentation at https://facebook.github.io/react-native/docs/button.html
Now, say you do want to make super customizable button, for that you'll have to use views and touchable opacity. Something along the lines of this.
<TouchableOpacity onPress={...}>
{... button markup}
</TouchableOpacity>
You'll wrap that up in your own button component and use it.