Home > Enterprise >  Route parameters with a new path
Route parameters with a new path

Time:12-25

`

  1. I am trying to update the app to have /, /user/:userId, and /user/new routes and any other route displays a 404 message.

  2. I got Error please help. Error: Expected substring: "Unable to create a new user" Received string: "<div ><a href="/">Home<a href="/user/new">New User<a data-testid="user-1" href="/user/1">User1<a ..."`

//App.js
import React from "react";
import "./style.css";
import { Link, Route, Switch } from "react-router-dom";
import NoMatch from "./NoMatch";
import UserProfile from "./UserProfile";

function Home() {
  return <h1>Home</h1>;
}

function NewUser(){
  return <h1>Unable to create a new user</h1>;
}

function App() {
  return (
    // No need to add <Router>, it has been added to ./index.js
    <div className="App">
      <div>
        <Link to="/">Home</Link>
      </div>
      <div>
        <Link to="/user/new">New User</Link>
      </div>
      
      {Array(10)
        .fill()
        .map((ignoredValue, index) => index   1)
        .map((id) => (
          <div key={id}>
            <Link to={`/user/${id}`} data-testid={`user-${id}`}>
              User{id}
            </Link>
          </div>
        ))}
      // Setup routes with route paramaters as needed
      <Switch>
        <Route exact={true} path="/">
          <Home />
        </Route>
        <Route path="/user/:userId">
          <UserProfile />
        </Route>
        <Route path="/user/new">
          <NewUser />
        </Route>
        <Route>
          <NoMatch />
        </Route>
      </Switch>

    </div>
  );
}

CodePudding user response:

Link components are used after the route they need to access has been defined prior in router context (in someplace higher up the component hierarchy). Hence I think you may have to define your routes setup in the parent component of <App /> because the routing context cannot not be correctly inferred else.

CodePudding user response:

I think the error is coming from Array(10).fill() expression. Can you try it again by modifying this expression? To me Array(10).fill() returning undefined. If you want to generate an Array that has elements 1 up to 10, use the following snippet instead.

[...Array(10).keys()] 
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

OR

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Related