JacobViti
2 min readAug 13, 2021

--

Hiding Child Components from a Parent with React.js

Hiding child components is an interesting concept. There are many apps that need to show stuff to the user, but they don’t need to be on the page all the time. This can be something as simple as information or instructions. Or it could be something like a form the user needs to fill out, like a survey. Here is how I found that this can be achieved with React.js.

We do this first by setting a state about the status of each child.

State

I set state of show1, show2, and show3 as false. Later in the app, when we want to render a child we will check state for a true or false. If true, the child will be rendered. If false, the child will not be rendered.

Another thing we need is a way to change this state.

hideComponent()

In hideComponent() we check to see what button is pressed. When that happens, we will change the state for that child. We check what child is hit with a switch statement. When the case is hit, it will alter the state for only that child.

Then we have to put it all together in the render

render()

Here is where we render the child components and buttons. First, we get each boolean from the state and save that in a variable. Then, we will return each child component. We also put the boolean with the child component, so the child won’t show unless the state is set as true. After that we have the buttons with hideComponent(). We also send what button was pressed to hideComponent() so we know what child should be shown.

You can see this time demo here: https://i.gyazo.com/ab9225d90cf64b8e258130516f6659d1.mp4

I feel like learning how to hide a child component could prove to be valuable when needed. It’s something I will keep in the back of my head whenever I create a new project. If you want to see more of my projects, you can check out my GitHub here:https://github.com/JakeKViti.

--

--