Search code examples
javascriptreactjsreactstrap

How handle change value of input select in React JS?


I am trying to build a form.

I have a Class extends React.Component that contains a constructor like this:

constructor(props) {
    super(props);
    this.state = {
      name: '',
      dataId: '',
      isactive: '',
    };
    this.handleCreateChange = this.handleCreateChange.bind(this);
}

This is the method to execute after the form submission
(I use dispatch to execute my action):

doCreateTarif = e => {
    e.preventDefault();
    let postData = {
      name: this.state.name,
      dataId: this.state.dataId,
      isactive: this.state.isactive,
    };
    console.log(postData);
    this.props.dispatch(createData(postData))
};

This method can handle all input changes:

handleCreateChange = e => {
    const target = e.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
};

Inside the render() function, before the return, I declare this:

const { data } = this.props;

structure data from props looks like this:

data = [
  {
    _id: "a1G23e25vaus6DVa7Sv",
    volume: 100,
  },
  {
    _id: "e1D23f25vaus6ASa7saA",
    volume: 100,
  },
]

Inside the return, I have a form that looks like this:
(I use reactstrap that's why my tags are like so: <Form>, <CustomInput/>, etc.) :

<Form onSubmit={this.doCreateTarif}>
<CustomInput
  onChange={this.handleCreateChange}
  type="switch"
  id="exampleIsActive"
  name="isactive"
  label="Turn on this if True"
/>
<Input
  onChange={this.handleCreateChange}
  type="text"
  name="name"
  id="exampleNama"
  placeholder="Nama"
/>
<Input onChange={this.handleCreateChange} type="select" name="dataId" id="exampleSelect">
  {
    data.map(item => {
      return (
        <option value={item._id}>{item.volume}</option>
      )
    })
  }
</Input>
<Button color="warning" className="px-5" type="submit">
  Create
</Button>
</Form>

This is result of console.log(this.state):

name: "ad"
dataId: ""
isactive: true


The value of state name and isactive work fine.
but the value of dataId is just an empty string, "".
I just wanna set _id from const { data } = this.props; as value of dataId in state.


Solution

  • I notice that you've used the Input, with the upper case I, which seems to be a customized component. I think your upper case Input component might not necessarily be paired up with the lower case option component.

    Or you might try to put your onchange callback and name on all those option components.

    Or do you have a customized Select component for your drop-down list?

    For controlled components, value attribute and onChange callback are both set on the input/select element. See how these components are used in react: the select & option pair