2

I am adding dynamically input fields.I want to get it's value .can you please tell me how I will get it's value

here is my code https://codesandbox.io/s/adoring-meninsky-hu3f8

return (
    <div className="App">
      <Form>
        {state.inputs.map(input => (
          <KeyValue />
        ))}
        <Button type="button" primary onClick={appendInput}>
          Add
        </Button>
      </Form>
    </div>
  );

I want to get it's value how ?

any update

2 Answers 2

1

Here is my solution https://codesandbox.io/s/pensive-lake-erynd

pass function to KeyValue component to get values when input changes

  const handleChangeKeyValues = name => value => {
    setState(prevState => {
      const newValues = {
        ...prevState.values,
        [name]: value
      };

      return {
        ...prevState,
        values: newValues
      };
    });
  };

and receives values from props and handle inputs in KeyValue component

const KeyValue = ({ onChange, values = { firstName: "", lastName: "" } }) => {
  const handleChangeInput = event => {
    const { value, name } = event.target;

    const newFormValue = { ...values, [name]: value };

    onChange(newFormValue);
  };

  return (
    <Form.Group widths="equal">
      <Form.Input
        value={values.firstName}
        fluid
        label="Key"
        name="firstName"
        placeholder="First name"
        onChange={handleChangeInput}
      />
      <Form.Input
        value={values.lastName}
        fluid
        label="Value"
        name="lastName"
        placeholder="Last name"
        onChange={handleChangeInput}
      />
      <Icon style={{ top: 30, position: "relative", left: 10 }} name="delete" />
      <Form.Input
        style={{ display: "none" }}
        fluid
        label=""
        placeholder="Last name"
      />
    </Form.Group>
  );
};

Store values in state under unique name for each inputs

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

Comments

1

I will put a name for each input and pass it a onChange function. Then in my onChange function i will set my State depend on the name.

Function

onChange = e => {
  this.setState({[e.target.name] : e.target.value});
}

Render

render(){
return (
    <div className="App">
      <Form>
        {state.inputs.map(input => (
          <KeyValue name={input.name} value={this.state[input.name]} onChange={this.onChange } />
        ))}
        <Button type="button" primary onClick={appendInput}>
          Add
        </Button>
      </Form>
    </div>
  );

}

1 Comment

but it is generating dynamically

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.