I need to clear the second select if it already has a selected value, in case the first one selects B
.
When cleaning it requires that the value be removed
, disabled
and that it has the Select...
option by default.
import React, { useState } from "react";
import { Form, Col, Button } from "react-bootstrap";
const App = () => {
const [data, setData] = useState({
to: "",
from: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setData((prevState) => ({
...prevState,
[name]: value,
}));
};
return (
<Form>
<Form.Row>
<Form.Group as={Col} md="auto">
<Form.Label>to</Form.Label>
<Form.Control
required
name="to"
as="select"
placeholder="to"
onChange={handleChange}
>
<option hidden value="" selected>
Select...
</option>
<option value="A">A</option>
<option value="B">B</option>
</Form.Control>
</Form.Group>
<Form.Group as={Col} md="auto">
<Form.Label>from</Form.Label>
<Form.Control
required
name="from"
as="select"
placeholder="from"
onChange={handleChange}
>
<option hidden value="" selected>
Select...
</option>
<option value="A">A</option>
<option value="B">B</option>
</Form.Control>
</Form.Group>
<Button variant="primary">Ok</Button>
</Form.Row>
</Form>
);
};
export default App;
How can I modify the code above to do what I commented? Thanks!
what you have here is cascading
issue your second select depends on the first select. In your handle change you can do this
const handleChange = (e) => {
const { name, value } = e.target;
if(name === 'to' && data.from){
setData((prevState) => ({
...prevState,
[name]: value,
from: ''
}));
} else {
setData((prevState) => ({
...prevState,
[name]: value,
}));
}
};
We are checking whether the value we are changing is the first select and also if the second select already has a value. If yes then we are clearing the value in the second select.
Also since you are using the state to preserve the form values, you need to add the value
prop to your component to make it as Controlled Component .
<Form.Control
required
name="to"
as="select"
placeholder="to"
value={data.to} // add this prop
onChange={handleChange}
>
<option hidden value="">
Select...
</option>
<option value="A">A</option>
<option value="B">B</option>
</Form.Control>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.