Professor_Joykill Professor_Joykill - 7 months ago 57
React JSX Question

How do I set property name to variable?

I am working on an online class, for which we have to build a list tracker application using react. I have had issues when trying to set the state of one of my classes. In this state I have a variable which is equal to an object. I am attempting to variably set both the name and value of this object, however I was uncertain on how to set the name variably.

let name = this.props.idName;
this.setState((prevState) => {
return {
newItem: { name: item}
};
}, () => {
this.props.addItem(this.state)
});


As you can see, I try to set the key in this object equal to the variable
name
, however this just sets it to the value of
name
rather than the value of the the
name
variable.

Answer Source

You can try this. Just enclose the name in square brackets. More on this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names.

let name = this.props.idName;
this.setState((prevState) => {
    return {
        newItem: { [name]: item}
    };
}, () => {
this.props.addItem(this.state)
});

var k = "key";

var obj = {[k]: "VALUE"}

console.log(obj);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download