简体   繁体   中英

How to add a route that will render a component using react-router-dom?

Presently, the following code is in the component SinglePostPage :

        <section>
            <article className="post">
                <h2>{post.title}</h2>
                <p className="post-content">{post.content}</p>
                <Link to={`editPost/${post.id}`} className="button">
                    Edit Post
                </Link>
            </article>
        </section>

The EditPostForm component contains the form to edit a post. How can I add a route to render the EditPostForm component when someone clicks on the Link ?

My App.js is as follows:

function App() {
  return (
    <Router>
      <Navbar />
      <div className="App">
        <Switch>
          <Route
            exact
            path="/"
            render={() => (
              <React.Fragment>
                <AddPostForm/>
                <PostsList/>
              </React.Fragment>
            )}
          />
          <Route exact path="/posts/:postId" component={SinglePostPage} />
          <Redirect to="/" />
        </Switch>
      </div>
    </Router>
  )
}

export default App

I believe you can just add a new route to App.js. For example:

function App() {
  return (
    <Router>
      <Navbar />
      <div className="App">
        <Switch>
          <Route
            exact
            path="/"
            render={() => (
              <React.Fragment>
                <AddPostForm/>
                <PostsList/>
              </React.Fragment>
            )}
          />
          <Route exact path="/posts/:postId" component={SinglePostPage} />
          <Route exact path="/editPost/:id" component={EditPostForm} />
          <Redirect to="/" />
        </Switch>
      </div>
    </Router>
  )
}

export default App;

and then in SinglePostPage your path for the link is slightly wrong, it should be:

<Link to={`/editPost/${post.id}`}>...</Link>

You were missing first '/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM