Ramzan Chasygov Ramzan Chasygov - 3 months ago 12
Javascript Question

Transfer state from childComp to the parentComp

I have

two component
s and i need to transfer
stat
e from
children component
to the
parent component


class Parent Component {
this.state = {text: hahaha}
this.props.action(text, data)

<Children Component />
<button onClick={this.props.action(text, data)}
}

class Children Component {
this.state = {date: 12.12.12}
}


Another little tricky it's i have
redux-action
in Parent Component, that takes two parameters
text and date
, in sum when i click button i need to transfer
state
from
childComp
to the
parentComp
and then create action with two parametres in
parentComp
. So how i can do that?

Answer Source

Refer component communication

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            content: 'initial'
        }
        this.updateParentState = this.updateParentState.bind(this);
    }

    updateParentState(content){
        this.setState({
            content: content
        })
    }

    render(){
        let { content } = this.state;
        return <div>
            <Child updateParentState={this.updateParentState}/>
            <h1>{ content }</h1>
        </div>
    }
}

class Child extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            value: 'initial'
        }
        this.handleParentState = this.handleParentState.bind(this);
        this.changeContent = this.changeContent.bind(this);
    }

    handleParentState(content){
        let { updateParentState } = this.props;
        let { value } = this.state;
        updateParentState(content);
    }

    changeContent(event){
        this.setState({
            value: event.target.value
        })
    }

    render(){
        let { value } = this.state
        return <div>
            <input value={value} onChange={this.changeContent}/>
            <button onClick={this.handleParentState}>Update Parent State</button>
        </div>
    }
}