Nitish Phanse Nitish Phanse - 1 month ago 18
React JSX Question

Props in state anti pattern

So i was reading the react docs which suggest using props in state is considered to be an anti pattern. I wanted to know what the write way is. I have a parent state container passing data to a child component which also has a state.

constructor(props) {
this.state = {
name = this.props.name
}
}


So i was wondering is it ok if i update the state in the CDM method

constructor(props) {
this.state = {
name = ''
}
}

componentDidMount() {
this.setState({name : this.props.name})
}


Any help or discussion here would be grateful.

Answer

Using props in state is a big no no. Here is an example how to do deal with situations like these

class Parent extends Component {
    state = {
        name: 'John Doe'
    }

    updateName = (name) => {
        this.setState({ name });
    };

    render() {
        return (
           <div>
                <label>Your Name</label>
                <Input value={this.state.name} updateName={this.updateName} />
           </div>
        );
    }
}

class Input extends Component {
    handleUpdate = (e) => {
        this.props.updateName(e.target.value);
    };

    render() {
        return <input value={this.props.value} onChange={this.handleUpdate} />
    }   
}