Reputation: 55
There are multiple input values in a prop, but the value I require is in state. I am said not to initialize this.props=this.state as props is read-only.
I had tried this.props=this.state and it did work.
const prevHouse = this.props.house; // This has multiple input values
prevHouse.rent = this.state.rent; //State is given input value
Is the above use of syntax is correct and what is the solution for this ?
Update : changing this.props.house to prevHouse in above
Upvotes: 0
Views: 607
Reputation: 650
You can initialize state the same with props like this using spread operator
constructor(props) {
super(props)
this.state = {
...props //this mean the value of state will filled with all of the object values in props object without need assigning one by one object values
}
}
Upvotes: 0
Reputation: 619
You can make a copy of the props and put it into the state. If your goal is to change state in the parent's component state from the child. You need to use Context Api or Redux
Upvotes: 1
Reputation: 410
You could pass your prop value into state when the component mounts. You could do this as follows using the componentDidMount
lifecycle method:
componentDidMount() {
this.setState({
rent: this.props.house.rent
})
}
This way, when the component mounts your state value rent
will be the value of this.props.house.rent
. You could then do this for each of the props you need in state.
Some more info on ComponentDidMount can be found at the React Documentation
Upvotes: 0