Casandra
Casandra

Reputation: 160

How to pass the state true or false from a child to the parent- React

I have two components, one parent (Widgets) and another son (Telefono). The "Telefono" component has the notInCall status and with it I paint or not a certain part of the code. On the other hand I have the showComponent() function that is in the parent with which I show or not the child component (Telefono) and two other components. I need to recover from the parent, in the showComponent() function the current status (true or false) of notInCall but I do not know how to do it.

Edit: I think I have not explained well. In the child I use a conditional this.state.notInCall to show or not part of the code. I need to pass the true or false response to the parent. If {this.state.notInCall ? (some code) : (another code)}. If this.state.notInCallon the child is true do one thing and if it is false do another

This is my parent component (Widgets)

class Widgets extends Component {   
    constructor(props) {
        super(props);
        this.state = {
            componente: 1,
            //notInCall: false,
        };
        this.showComponent = this.showComponent.bind(this);
    }

    showComponent(componentName) {
        /*this.setState({
            notInCall: false,
        });*/
        if(this.state.notInCall === false){
            this.setState({
                componente: Telefono,
                addActive: Telefono,
            });
            alert(this.state.notInCall + ' running? Componente:' + componentName);
            console.log(this.state.notInCall);
        }else{
            alert('verdad');
            this.setState({
                componente: componentName,
                addActive: componentName,
            });            
        }
        console.log(this.state.notInCall);
    }

    renderComponent(){
        switch(this.state.componente) {
            case "ChatInterno":
                return <ChatInterno />
            case "HistorialLlamadas":
                return <HistorialLlamadas />
            case "Telefono":
            default:
                return <Telefono showComponent={this.showComponent}/>
        }
    }

    render(){
        return (
            <div id="bq-comunicacion">
                <nav>
                    <ul>
                        <li><button onClick={() => this.showComponent('Telefono')} id="mn-telefono" className={this.state.addActive === 'Telefono' ? 'active' : ''}><Icon icon="telefono" className='ico-telefono'/></button></li>
                        <li><button onClick={() => this.showComponent('ChatInterno')} id="mn-chat" className={this.state.addActive === 'ChatInterno' ? 'active' : ''}><Icon icon="chat-interno" className='ico-chat-interno'/></button></li>
                        <li><button onClick={() => this.showComponent('HistorialLlamadas')} id="mn-llamadas" className={this.state.addActive === 'HistorialLlamadas' ? 'active' : ''}><Icon icon="historial-llamadas" className='ico-historial-llamadas'/></button></li>
                    </ul>
                </nav>
                <div className="content">
                    { this.renderComponent() }
                </div>
            </div>
        );
    }
}

This is my child component (Telefono)

class Telefono extends Component {
    constructor(props) {
        super(props);

        this.inputTelephone = React.createRef();

        ["update", "reset", "deleteClickNumber", "closeAlert", "handleKeyPress",].forEach((method) => {
            this[method] = this[method].bind(this);
        });

        this.state = this.initialState = {
            notInCall: true,
            isRunning: false,
        };
    }

    phoneCall(e){
        e.preventDefault();
        this.props.showComponent(this.state.notInCall);

        if(this.state.inputContent.length < 2){
            this.setState({
                warningEmptyPhone: true,
            });

            this.change = setTimeout(() => {
                this.setState({
                    warningEmptyPhone: false
                })
            }, 5000)
        }else if(this.state.inputContent.length >= 2 ){
            this.setState({
                notInCall: !this.state.notInCall,
                isRunning: !this.state.isRunning,
                componente: 'Telefono',
            }, 
                () => {
                    this.state.isRunning ? this.startTimer() : clearInterval(this.timer);
                    //console.log(this.componente);
                });
        }
    }

    render(){
        return(
            <div className="pad sb-content">
                {this.state.notInCall
                    ? (
                        <>
                        <div className="dial-pad">
                            <div className="digits">
                                <Numbers numbers={this.state.numbers}
                                />
                            </div>
                        </div>
                        <div className="btn-call call" onClick={this.phoneCall.bind(this)}>
                            <Icon icon="telefono" className='ico-telefono'/>
                            <span>LLAMAR</span>
                        </div>
                        </>
                    )
                    : (
                        <div className="call-pad">
                            <div id="ca-number" className="ca-number">{this.state.inputContent}</div>
                            <TimeElapsed id="timer" timeElapsed={timeElapsed}/>
                        </div>    

                    )}
            </div>
        );
    }
}

Thanks for the help

Upvotes: 0

Views: 1140

Answers (2)

narcello
narcello

Reputation: 499

You can create a handle in parent, like:


handleNotInCall (notInCall) {
  // handle here
}

And pass this handle to child:

<Telefono handleNotInCall={this.handleNotInCall} />

In child you call like this:


this.props.handleNotInCall(<param here>)

UPDATE

on parent: On Parent:

  • put notInCall in state
  • create a handle for notInCall
  • pass for child handle and state
// state
this.state = {
  componente: 1,
  notInCall: false,
};
// create a handle
handleNotInCall (notInCall) {
  this.setState({notInCall});
}
// pass both for child
<Telefono handleNotInCall={this.handleNotInCall} notInCall={this.state.notInCall}/>

In child, where you do:

this.setState({
  notInCall: !this.state.notInCall,
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})
// change for
this.props.handleNotInCall(!this.props.notInCall)
this.setState({
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})

// where you use for compare 
this.state.notInCall ? 
// change for:
this.props.notInCall ?

Upvotes: 1

Ragnar
Ragnar

Reputation: 88

If I understood your problem correctly, the answer of Marcello Silva is correct.

Say you have this:

class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            childAvailable: true,
        };
    }

    handleAvailability = status => {
        this.setState({ childAvailable: status });
    }

    render() {
        const { childAvailable } = this.state;

        if (!childAvailable) {
            return (...); // display whatever you want if children not available
        } else {
            return (
                <div>
                    {children.map(child => {
                        <Children
                            child={child}
                            statusHandler={this.handleAvailability}
                        />
                    }
                </div>
            );
        }
    }
}

and

class Children extends React.Component {
    constructor(props) {
         super(props);

         this.state = {
             available: true,
         };
    }

    handleClick = e => {
        const status = !this.state.available;
        this.setState(prevState => { available: !prevState.available });

        // if you call the handler provided by the parent here, with the value
        // of status, it will change the state in the parent, hence
        // trigger a re render conditionned by your value
        this.props.statusHandler(status);
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick}>Click me to change status</button>
            </div>
        );
    }
}

Doing this will call the function you passed as prop to your children in your parent. This function sets your state, and therefore triggers a re render once the state has been set, so you'll be rendering whatever you want considering the new value of childAvailable.

EDIT: After seeing the comment on said answer, I'd like to add that you can of course call your handleClick method from your conditions on this.state.notInCall.

Upvotes: 0

Related Questions