ReactJS Initial State Example

image
  • getInitialState() is life cycle method of a ReactJS component.
  • The state can be updated using setState() method.This method takes an JavaScript object.
  • In this demo, “We will learn how to create a initial state object and how to change the value of the state”.
  • Below code contains a react component having two buttons and a text string.The default color of the applyState is red.When user click these button the state value gets change to blue and vice verse.
<!doctype html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>ReactJS Component Example</title>
<script src="http://fb.me/react-0.8.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.8.0.js"></script>
</head>

<body>
<script type="text/jsx">
/*** @jsx React.DOM */
var myname = React.createClass({
getInitialState: function() {
return{
textColor: {color: 'red'}
};
},
changeStateToBlue: function() {
this.setState({textColor: {color: 'blue'}})
},
changeStateToRed: function() {
this.setState({textColor: {color: 'red'}})
},
render:function(){
return (
<div>
<h1 style={this.state.textColor}>
Sandeep Kumar Patel
</h1>
<button onClick={this.changeStateToBlue}>
Change State to Blue
</button>
<button onClick={this.changeStateToRed}>
Change State to Red
</button>
</div>
)
}
});
React.renderComponent(<myname/>,document.body)
</script>
</body>
</html


  • The output of the above code is embedded in below JSBIN link.
ReactJS Component Example