Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding parent react component, when you click on a child component

I am new to javascript world and creating a front end application using react.js. Following is a scenario I am unable to code. I want to display a list of items such that when I click any one item in the list, I ONLY see the details of the chosen item and remove the view of items. I tried to use react-router library, but react-router works in a nested fashion, where details of the child component are rendered under the parent component(the list of items). It does not hide the parent component.

like image 355
Harsha Rastogi Avatar asked Sep 01 '25 22:09

Harsha Rastogi


1 Answers

You can pass a function to the child onClick prop from parent component, and handle the hidden event in that function. A simple implement looks like this:

class Parent extends React.Component {
    constructor() {
        super(...arguments);
        this.state = {hide: false};
    }
    handleChildClick() {
        this.setState({hide: true});
    }
    render() {
        const {hide} = this.state;
        if (hide) {
            return null;
        }
        return <Child onClick={this.handleChildClick.bind(this)} />;
    }
 }

 class Child extends React.Component {
     render() {
         const {onClick} = this.props;
         return <button onClick={onClick}>Hide Parent</button>;
     }
 }
like image 171
Philip Tzou Avatar answered Sep 03 '25 13:09

Philip Tzou