Replace this.handleClick with this.props.onClick in Board’s renderSquare. Now we need to decide which component should own the history state. Detecting changes in mutable objects is difficult because they are modified directly.
We’ll want the top-level Game component to display a list of past moves. It will need access to the history to do that, so we will place the history state in the top-level Game component. If we mutated the squares array, implementing time travel would be very difficult. Note how in handleClick, we call .slice() to create a copy of the squares array to modify instead of modifying the existing array. We will explain why we create a copy of the squares array in the next section. Since the Square components no longer maintain state, the Square components receive values from the Board component and inform the Board component when they’re clicked.
- You don’t need to go anywhere and You can also learn at your own pace.
- The challenges are inspired from modern real world projects to make sure that you’re learning the best practices, one step at a time.
- They also have a very active online community where you can ask questions in the comments section and receive assistance.
- We will also replace reading this.state.history with this.state.history.slice(0, this.state.stepNumber + 1).
In React terms, the Square components are now controlled components. We have not defined the handleClick() method yet, so our code crashes. If you click a square now, you should see a red error screen saying something like “this.handleClick is not a function”. To collect data from multiple children, or to have two child components communicate with each other, you need to declare the shared state in their parent component instead. The parent component can pass the state back down to the children by using props; this keeps the child components in sync with each other and with the parent component. The React DevTools let you check the props and the state of your React components.
What Is React?
React components can have state by setting this.state in their constructors. This.state should be considered as private to a React component that it’s defined in. Let’s store the current value of the Square in this.state, and change it when the Square is clicked. Add a file named index.js in the src/ folder with this JS code. Add a file named index.css in the src/ folder with this CSS code. You don’t have to complete all of the sections at once to get the value out of this tutorial.
- These are good and made free by their instructor for educational purposes and perfect to start with.
- Topics include variables, operators, functions, arrays, objects, and loops.
- In this tutorial, we’ll show how to build an interactive tic-tac-toe game with React.