I'm making a static web app with React. It has more pages so I'm using the react-router-dom, but when i use the Link tag it shows up not just on the page I want it on but also on the page it's suppose to redirect. Except for that everything works just fine: the page it's pointing at is rendering just fine, but with the link in the bottom left corner. Can anyone look over my code and tell me what I am doing wrong?
I only want the link 'To Do List' to show up here:
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { Link } from 'react-router-dom'
import Todo from '../apps/todo/Todo'
class Projects extends Component {
render() {
return (
<Router>
<div>
<Route exact path="/todo" component={Todo} />
<Link style={projectsTodo} href="/todo">
To Do List
</Link>
</div>
</Router>
)
}
}
The link shows up here:
import React, { Component } from 'react'
import Header from './layout/Header'
import Todos from './Todos'
import uuid from 'uuid'
class Todo extends Component {
state = {
todos: [
{
id: uuid.v4(),
title: 'Learn React',
completed: false,
},
{
id: uuid.v4(),
title: 'Find suitable web hosting service',
completed: false,
},
],
}
delTodo = id => {
this.setState({
todos: [...this.state.todos.filter(todo => todo.id !== id)],
})
}
render() {
return (
<div>
<Header />
<Todos todos={this.state.todos} delTodo={this.delTodo} />
</div>
)
}
}
export default Todo
This is happening because you are rendering the Link without any specified route (so it is rendered on all routes). See the first example of React Router to get a better understanding.
If you don't want this to happen, then define another component Home
(for example) that will hold the Link and add another Route to your Router that will render that component.
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { Link } from 'react-router-dom'
import Todo from '../apps/todo/Todo'
const Home = props => {
return (
<div>
<h2>Home</h2>
<Link style={projectsTodo} href="/todo">
To Do List
</Link>
</div>
)
}
class Projects extends Component {
render() {
return (
<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/todo" component={Todo} />
</div>
</Router>
)
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments