ReactJS Initial State Example

  • 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">

<meta charset="UTF-8">
<title>ReactJS Component Example</title>
<script src=""></script>
<script src=""></script>

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

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