NAMAN AGGARWAL
NAMAN AGGARWAL

Reputation: 141

How to pass props in routes?

I have the selected country in Country.js. What I want to do is pass this country to Home.js and also render Home.js when the user clicks the button.

App.js

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Country} />
        <Route path="/home" component={Home} />
      </Switch>
    </BrowserRouter>
  );
};

Country.js

return (
    <div className="container">
      <label htmlFor="country">Country</label>
      <select name="country" id="country" onChange={handleSelect}>
        <option value="-1">--Country--</option>
        <option value="in">India</option>
        <option value="jp">Japan</option>
        <option value="us">USA</option>
        <option value="br">Brazil</option>
        <option value="ch">China</option>
        <option value="sr">Sri lanka</option>
      </select>
      <Link to="/home">
        <button type="submit">Proceed</button>
      </Link>
    </div>
  );

Upvotes: 1

Views: 274

Answers (1)

Steve
Steve

Reputation: 8809

To pass the selected country to Home, its state needs to be managed at one level above Home.

const App = () => {
  const [country, setCountry] = useState();

  return (
    <BrowserRouter>
      <Switch>
        <Route
          exact
          path="/"
          render={(props) => (
            <Country
              {...props} // pass through router props if needed
              country={country}
              onChangeCountry={setCountry}
            />
          )}
        />
        <Route
          path="/home"
          render={(props) => (
            <Home
              {...props} // pass through router props if needed
              country={country}
            />
          )}
        />
      </Switch>
    </BrowserRouter>
  );
};

Country.js:

const Country = ({country, onChangeCountry}) => {
  const handleSelect = useCallback(
    (event) => {
      if (typeof onChangeCountry === 'function') {
        onChangeCountry(event.target.value);
      }
    },
    [onChangeCountry]
  );

  return (
    <div className="container">
      <label htmlFor="country">Country</label>
      <select
        name="country"
        id="country"
        value={country}
        onChange={handleSelect}
      >
        <option value="-1">--Country--</option>
        <option value="in">India</option>
        <option value="jp">Japan</option>
        <option value="us">USA</option>
        <option value="br">Brazil</option>
        <option value="ch">China</option>
        <option value="sr">Sri lanka</option>
      </select>
      <Link to="/home">
        <button type="submit">Proceed</button>
      </Link>
    </div>
  );
};

Upvotes: 2

Related Questions