Reputation: 55
I'm trying to change the name property of an input as the state of my component changes.
in short, this is What i'm trying to do.
let displayInputElement = (
<input
type="text"
name = {pips}
placeholder="Type your answer here"
className=" form-control"
/>
);
displayInputElement.props.name = "chicken";
But I'm getting the below error
TypeError: Cannot assign to read only property 'name' of object '#'
Please how can i achieve the below in react
displayInputElement.props.name = "chicken";
let pips = displayInputElement.props.name;
displayInputElement = (
<input
type="text"
name = "chicken"
placeholder="Type your answer here"
className=" form-control"
/>
);
Upvotes: 2
Views: 18271
Reputation: 1079
I was facing the same issue while working with React State. I have found the simple solution and its worked for me. Just you will have to do a deep copy of your array. It may be enough with:
let newData = data.map((item) =>
Object.assign({}, item, {selected:false})
)
Thanks
Upvotes: 1
Reputation: 1207
I think you should make displayInputElement as a component so you can pass whatever you want through the props argument
let DisplayInputElement = (props) =>(
<input
type="text"
name = {props.name}
placeholder="Type your answer here"
className=" form-control"
/>
);
const state = {
name:"myrrtle"
}
ReactDOM.render(<DisplayInputElement name={state.name} />, mountNode);
You can't set props by writing DisplayInputElement.props.name="chicken"
as props are meant to be read.
I have just taken an example state to demonstrate what I mean. Hope this helps you.
Upvotes: 1
Reputation: 3296
Props are read only.
You can create a new variable with the name prop, then change that variable, or, use a callback to update the parent component's property which can be passed down to this component.
let newName = displayInputElement.props.name;
newName = "chicken";
Or something like this:
this.state = {
name: this.props.name;
}
this.setState({
name: "chicken";
}), () => {
callbackToParent(this.state.name);
}
Upvotes: 0