We can include components within other components.
Embed the Car
component within the Garage
component.
class |
React emphasizes code reuse, so it’s beneficial to place some components in separate files. To do this, create a new file with a .js extension and include the component code. Ensure the file begins with importing React (as usual) and ends with export default Car;.
Here is the new file, named Car.js.
This is the new file, called Car.js.
import |
To use the Car component, you need to import the Car.js file into your application.
Now that we’ve imported the Car.js file into the application, we can use the Car component as if it were created directly in this file.
import |
React Class components include a built-in state object, which we used earlier in the component constructor section. The state object stores property values specific to the component.
When the state object updates, the component re-renders.
The state object is initialized within the constructor.
Define the state object within the constructor method.
class |
The state object can include as many properties as needed.
Define all the properties required by your component.
class |
Access the state object anywhere in the component using the this.state.propertyName syntax.
Access the state object within the render() method.
To update a value in the state object, use the this.setState() method. When a value in the state object is modified, the component will re-render, reflecting the changes in the output based on the new value(s).
Add a button with an onClick event that will update the color property.
class |
Always use the setState() method to update the state object; it ensures the component is aware of the change and triggers the render() method (along with other lifecycle methods). |