Changing route parameters when a different dropdown option is selected in React
Attach an onChange
event to the select and in it push to the history
object that the router passes as a prop.
Edit:
here's an example https://codesandbox.io/s/w031p82nr5
Related videos on Youtube
K. Smith
Updated on June 04, 2022Comments
-
K. Smith almost 2 years
I have a dropdown in my application, and I want it so that when a user selects a different option from the dropdown, it should update the url.
For example, if I have a
DropDown
component like such:class DropDown extends React.Component { render() { return ( <select> <DropDownOption name="foo" /> <DropDownOption name="bar" /> </select> ); } }
And a
DropDownOption
component like such:import { Link } from 'react-router-dom'; class DropDownOption extends React.Component { render() { return ( <option> <Link to={`/value=${this.props.name}`}> </Link> </option> ); } }
If the user clicks on the dropdown then selects 'foo', the url would change to for example: "
localhost:3000/value=foo
", and when they select 'bar', it would change to "localhost:3000/value=bar
"However, this doesn't work because
<option>
tag cannot have an<a>
tag inside of it, but I was hoping to do it using<Link>
from thereact-router-dom
module because I have been using it in other places (eg. for buttons) to change the route parameters and it has worked fine.Any suggestions how I can implement this?