I am working on an app using useNavigate to go from page to page but am having trouble. Currently, the button click will cause the url to update, but the corresponding page doesn't render. Any help as to what I'm doing wrong?
Here is my button component:
import Fab from '@material-ui/core/Fab';
import AddIcon from '@mui/icons-material/Add';
import { useNavigate } from "react-router-dom";
const FabButton = () => {
let navigate = useNavigate();
return (
<div >
<Fab
onClick={() => navigate(`/add`)}>
<AddIcon />
</Fab>
</div>
)
};
export default FabButton;
My App.js:
import React from 'react';
import { Router, Routes, Route } from 'react-router-dom';
import history from '../history';
import AddPage from './AddPage';
import HomePage from './HomePage';
class App extends React.Component {
render() {
return (
<Router location={history.location} navigator={history} >
<Routes >
<Route exact path="/add" element={ <AddPage title="One Rep - Add" /> } ></Route>
<Route exact path="/" element={ <HomePage title="One Rep - Home" /> } ></Route>
</Routes>
</Router>
)
}
};
export default App;
My history.js:
import { createHashHistory } from 'history';
export default createHashHistory();
My AddPage.js:
export default AddPage;
import React, { useState } from 'react';
import Header from '../components/Header';
import { makeStyles } from '@material-ui/core/styles';
import { TextField, Button, InputAdornment } from '@material-ui/core';
const AddPage = () => {
const [moveData, setMoveData] = useState({ movementName:'', movementWeight: '' });
const handleSubmit = (e) => {
e.preventDefault();
};
return (
<div>
<Header title={"Add Movement"} />
<div>
<form onSubmit={handleSubmit} >
<div>
<TextField
name="movementName"
variant="outlined"
label="Movement Name"
style={{ width:200 }}
value={moveData.movementName}
onChange={(e) => setMoveData({ ...moveData, movementName: e.target.value })}
/>
<TextField
name="movementWeight"
variant="outlined"
label="One Rep Max"
style={{ width:200 }}
value={moveData.movementWeight}
InputProps={{endAdornment: <InputAdornment position="end">lb</InputAdornment>}}
onChange={(e) => setMoveData({ ...moveData, movementWeight: e.target.value })}
/>
</div>
<div>
<Button
variant="contained"
type="submit"
fullWidth >
Submit
</Button>
</div>
</form>
</div>
</div>
);
};
export default AddPage;
I am using react-router-dom ^6.3.0
CodePudding user response:
In react router v6 you should use BrowserRouter
instead of Router
. You can see an example in their documentation
So, in your case it should look like this
<BrowserRouter>
<Routes>
<Route
exact
path="/add"
element={<AddPage title="One Rep - Add" />}
></Route>
<Route
exact
path="/"
element={<HomePage title="One Rep - Home" />}
></Route>
</Routes>
</BrowserRouter>