Reputation: 405
Im new to React and Im creating a simple react app. I currently implement react-router. Im just want to ask what's the difference between this
<Route path="/projects/add" component={Addproject} />
to this
<Route path="/projects/:id" component={Projectitem} />
I cant seem to get it. When I click the link it says
TypeError: Cannot read property 'params' of undefined
and the AddProject Component wont show. It seems like its taking me to the ProjectItem Component despite me clicking the link to AddProject. Where did I go wrong?
Here is my router code.
<Router>
<div>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark fixed-top lead">
<div className="container">
<div className="navbar-brand pull-left">
<ul className="navbar-nav">
<li className="active"><Link className="navbar-brand" to="/">Home Page</Link></li>
</ul>
</div>
<div className="collapse navbar-collapse" id="navbarResponsive">
<ul className="navbar-nav ml-auto">
<li className="nav-item active">
<Link className="nav-link" to="/">
<i className="fa fa-fw fa-home"></i> Home
<span className="sr-only">(current)</span>
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/projects">
<i className="fa fa-fw fa-briefcase"></i> Projects
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/page1/Jason">Page 1</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/page2">Page 2</Link>
</li>
</ul>
</div>
</div>
</nav>
<Switch>
<Home>
<Route exact path="/" component={User} />
<Route exact path="/projects" component={Project} />
<Route path="/projects/add" component={Addproject} />
<Route path="/projects/:id" component={Projectitem} />
<Route path="/page1/:name" component={Page1} />
<Route path="/page2" component={Page2} />
</Home>
</Switch>
</div>
</Router>
I've been reading and I read something about match. Can someone please teach me how to use it. Thanks in advance.
Upvotes: 0
Views: 492
Reputation: 228
Try using your params in Projectitem component like this: const { params } = this.props.match
then you could use your id var like this: <p>Project ID:
{params.id}</p>
.
Upvotes: 0
Reputation: 405
Its seems that I've got a little understanding how this router works. I've read that
/projects/add
and
/projects/:id
are the same path. A quick solution would be
/projects/list/:id
and
/projects/add
But I dont want to do it like this. I would like to learn a much better approach rather than customizing my links. Thanks to anyone who would answer. Sorry im such a noobie. :(
Upvotes: 1