Skip to main content

--description--

One of the most important topics in React is state. State consists of any data your application needs to know about, that can change over time. You want your apps to respond to state changes and present an updated UI when necessary. React offers a nice solution for the state management of modern web applications.

You create state in a React component by declaring a state property on the component class in its constructor. This initializes the component with state when it is created. The state property must be set to a JavaScript object. Declaring it looks like this:

this.state = {

}

You have access to the state object throughout the life of your component. You can update it, render it in your UI, and pass it as props to child components. The state object can be as complex or as simple as you need it to be. Note that you must create a class component by extending React.Component in order to create state like this.

--instructions--

There is a component in the code editor that is trying to render a firstName property from its state. However, there is no state defined. Initialize the component with state in the constructor and assign your name to a property of firstName.

--hints--

StatefulComponent should exist and render.

assert(
(function () {
const mockedComponent = Enzyme.mount(
React.createElement(StatefulComponent)
);
return mockedComponent.find('StatefulComponent').length === 1;
})()
);

StatefulComponent should render a div and an h1 element.

assert(
(function () {
const mockedComponent = Enzyme.mount(
React.createElement(StatefulComponent)
);
return (
mockedComponent.find('div').length === 1 &&
mockedComponent.find('h1').length === 1
);
})()
);

The state of StatefulComponent should be initialized with a property firstName set to a string.

assert(
(function () {
const mockedComponent = Enzyme.mount(
React.createElement(StatefulComponent)
);
const initialState = mockedComponent.state();
return (
typeof initialState === 'object' && typeof initialState.firstName === 'string'
);
})()
);

The property firstName in the state of StatefulComponent should render in the h1 element.

assert(
(function () {
const mockedComponent = Enzyme.mount(
React.createElement(StatefulComponent)
);
const initialState = mockedComponent.state();
return mockedComponent.find('h1').text() === initialState.firstName;
})()
);

--seed--

--after-user-code--

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

--seed-contents--

class StatefulComponent extends React.Component {
constructor(props) {
super(props);
// Only change code below this line

// Only change code above this line
}
render() {
return (
<div>
<h1>{this.state.firstName}</h1>
</div>
);
}
};

--solutions--

class StatefulComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: 'freeCodeCamp!'
}
}
render() {
return (
<div>
<h1>{this.state.firstName}</h1>
</div>
);
}
};