'Linking components in React using React Router Link not working
I am new to React and I am creating a portfolio web page in which I am trying to connect two components with the Link component in react-router-dom (similar to href in HTML anchor tags). I used a button in my home page which when clicked will direct me to the 'projects' component in the same page. There's no error but when I click it nothing happens. Please help me solve this issue.
Below are the code snippets to index.js, where the Router path specified references the Projects Component where my projects are listed, and the Home Component where I added a button with the link to the path in the Router
Please let me know if I'm wrong in implementing the Router
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter, Route } from 'react-router-dom';
import {Projects} from './components/Projects';
ReactDOM.render(
<BrowserRouter>
<div>
<Route component={App} />
<Route path= "/projects" component={Projects} />
</div>
</BrowserRouter>,
document.getElementById('root')
);
Home Component:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Projects from './Projects';
export class Home extends Component {
render() {
return (
<div>
<Link to = '/projects' className="btn btn-primary btn-learn">
View Projects </Link>
</div>
)
}
}
export default Home
App.js that renders Home and Projects Components:
import './App.css';
import Home from './components/Home';
import Projects from './components/Projects';
import Skills from './components/Skills';
class App extends Component {
render() {
return (
<div>
<div>
<Home/>
<Skills/>
<Projects/>
</div>
</div>
);
}
}
P.S: All other explanations on SO about a similar issue talk about linking to another page which I'm confused about. I want to add a link that redirects to the component on the same page but not another webpage.
Solution 1:[1]
For anyone that is suffering like I did, I had to remove the <React.StrictMode> in order for my Link components to work.It is located in index.js.
Old Code:
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
New Code:
root.render(
<App />
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | okcowboy80 |