How to map dynamic property to element bracket function in react?

Viewed 671

Im trying to map a state property as value to a generated form input with react, but have been unsuccessful so far. The example below shows what im trying to do, but the wrong way as group.value is imported as a string, and wont be compiled into the value of the state variable. Does anyone know how to accomplish this? I need both the final object and property to be dynamically called (in this example frame and brand/year/model)

Map function:

return frameData.map((group) => {
            return (
                <div className="form-group">
                    <div className="col-sm-8">
                        <input
                            type="text"
                            className="form-control"
                            id={group.name}
                            name={group.name}
                            placeholder={group.placeHolder}
                            value={group.value}
                            onChange={(event) => this.updateValue(event)}
                        />
                    </div>
                </div>
            );
        });

dataset

const frameData = [
    {
        name: "frame-brand",
        placeHolder: "Brand",
        value: "{this.state.newSubmission.frame.brand}",
    },
    {
        name: "frame-year",
        placeHolder: "Year",
        value: "{this.state.newSubmission.frame.year}",
    },
    {
        name: "frame-model",
        placeHolder: "Model",
        value: "{this.state.newSubmission.frame.model}",
    },
];

state

    this.state = {
        newSubmission: 
          frame: {
            year: "",
            model: "",
            brand: "",
          }
    };
1 Answers

what you are trying to achieve is cool, but instead of passing the variable name i,e the entire state object, you can just pass the key and you can assign that to the <input /> component.

const frameData = [
    {
        name: "frame-brand",
        placeHolder: "Brand",
        value: "brand",
    },
    {
        name: "frame-year",
        placeHolder: "Year",
        value: "year",
    },
    {
        name: "frame-model",
        placeHolder: "Model",
        value: "model",
    },
];

and in the map function, you can use

return frameData.map((group) => {
        return (
            <div className="form-group">
                <div className="col-sm-8">
                    <input
                        type="text"
                        className="form-control"
                        id={group.name}
                        name={group.name}
                        placeholder={group.placeHolder}
                        value={this.state.newSubmission.frame[group.value]}
                        onChange={(event) => this.updateValue(event)}
                    />
                </div>
            </div>
        );
    });
Related