Changing route parameters when a different dropdown option is selected in React

10,497

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

Share:
10,497

Related videos on Youtube

K. Smith
Author by

K. Smith

Updated on June 04, 2022

Comments

  • K. Smith
    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 the react-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?