Hello, I am having problems routing from a button to a view in react, I already installed it react-router-dom
, but what happens to me is that if I click the signup button in the home view, it should redirect me to the route /test
, but it does not happen , what happens is that it marks the route in the url but the content of the view is rendered to me in the same home view and it is not seen (if I do not inspect html). My configuration is the following:
In views/home:
// React
import React from 'react';
// React router dom
import { Link } from 'react-router-dom';
// Style
import './style.sass';
import homeImage from '../../assets/images/home/home-image.png';
class Home extends React.Component {
render() {
return(
<div className="home-container">
<div className="home-content-left">
<h1 className="find-books-text">FIND BOOKS</h1>
<h1 className="find-books-text">YOU LIKE</h1>
<button><Link to='/test'>SIGN UP</Link></button>
</div>
<div className="home-image-picture">
<img src={homeImage} />
</div>
<div className="home-figure">
</div>
</div>
);
}
}
export default Home;
In index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// Context Provider
import AppProvider from '../src/context/context';
// React-bootstrap styles
import 'bootstrap/dist/css/bootstrap.min.css';
// React router dom
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
{/* <AppProvider> */}
<BrowserRouter>
<App />
</BrowserRouter>
{/* </AppProvider> */}
</React.StrictMode>,
document.getElementById('root')
);
Inside app.js:
// React
import React, { Fragment } from 'react';
// Components
import Home from '../src/views/Home/index';
import NavBar from './components/navbar';
// Routes
import Routes from './route';
function App() {
return (
<Fragment>
<Home />
<NavBar />
<Routes />
</Fragment>
);
}
Besides I have a folder in src/route where I have the routes:
// React
import React from 'react';
// React-router-dom
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
// Views
import Test from '../views/Test';
import Home from '../views/Home';
class Routes extends React.Component {
render() {
return (
<Switch>
<Route
path="/"
component={Home} exact/>
<Route
path="/test"
component={Test} />
</Switch>
);
}
}
export default Routes;
With the current configuration, when you want to hide the component
Home
routing to the componentTest
,Home
it is shown again, since it is positioned above<Routes>
, which is where the content for each route was specified:The content of the route "/" has already been configured, it directs towards the component
Home
, this insideRoutes
:So, just reconfigure the initial component tree in
App
:Here's a demo based on your original code:
Hope this answer is helpful.
try using the history property that your component receives, like so: