2

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"
  />
);

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.