How to use required props in a Reach Route component

Viewed 181

I'm using @reach/router with React. I create a route component with a required prop. I get prop type warnings when the app mounts but the route is not active.

This simple example is adapted from the @reach/router docs.

import React from "react";
import { render } from 'react-dom';
import PropTypes from 'prop-types';
import { Router, Link } from "@reach/router";

const App = ({ children }) => (
  <div>
    <nav>
      <Link to="/">Home</Link>{" "}
      <Link to="users/123">Bob</Link>{" "}
      <Link to="users/abc">Sally</Link>
    </nav>
    {children}
  </div>
);

const User = props => <h2>{props.userId}</h2>;

User.propTypes = {
  userId: PropTypes.string.isRequired
};

const Home = () => (
  <div>
    <h2>Welcome!</h2>
    <p>
      Select a user, their ID will be parsed from the URL and passed to the User
      component
    </p>
  </div>
);

render(
  <Router>
    <App path="/">
      <Home path="/" />
      <User path="users/:userId" />
    </App>
  </Router>,
  document.getElementById("root")
);

The code renders the Home component rather than the User component. Despite this I can see the following error in the console:

Failed prop type: The prop `userId` is marked as required in `User`, but its value is `undefined`.

I would not expect to see this error unless the component is rendered.

Is there a way to prevent this from happening?

I want to specify that the prop from the dynamic segment is required, using prop-types, but I don't want to see this prop warning.

1 Answers

You should want to put an / in front of your path inside your user component, like so:

<User path="users/:userId" /> <~ your code

<User path="/users/:userId" /> <~ Your solution

edit: You want to do the same for your links <Link to="users/abc">Sally</Link> <~ your code

<Link to="/users/abc">Sally</Link> <~ Your solution

Related