0

I have no idea why React Router won't work when I try navigating to the /addData component upon the click of a button. It works as it should when I try with the path but not when I click the button. I would like to know what I'm doing wrong. Please note, this is my first time with React Router. The version of React Router I'm using is react-router-dom": "^5.3.0 Here is the code.

App.js

import MainScreen from "./screens/main_screen/main_screen";
import AddDataScreen from "./screens/add_data/add_data";
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route exact path="/" component={MainScreen}>
          </Route>
          <Route path="/addData" component={AddDataScreen}>  //This is a blank page with Add Data written on it
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

export default App;

The component where the button is from which I intend to navigate:

import { Link } from "react-router-dom";

const FloatingButton = () => {

    const addScreen = () => {
        <Link to="/addData">Add Data</Link>
        console.log("Clicked")
    }

    return (
        <div className="floatingButton">
            
            <div className="addFloat" onClick={addScreen}>   //The button
                <IoMdAdd color={"white"} size={"20px"}/>
            </div>
            
        </div>
    );
}

export default FloatingButton;
coolhack7
  • 1,204
  • 16
  • 35

1 Answers1

1

Your addScreen function just returns Link which is a component, and this approach does not call any redirecting action (as you can see here, Link results in an <a> element).

You could use the useHistory hook to access the history object and push the addData route:

import { useHistory } from "react-router-dom";

  let history = useHistory();

  const addScreen = () => {
    history.push("/addData");
  }
Daniel Baldi
  • 794
  • 1
  • 9
  • Thanks for the answer. My question now is, when do we use Links to navigate between pages? – coolhack7 Nov 26 '21 at 13:05
  • This is mainly for semantic reasons. Using a `button` element to redirect users is semantically incorrect as you're supposed to use `a` for that. This answer has a more detailed explanation if you're interested: https://stackoverflow.com/a/64443954 – Daniel Baldi Nov 26 '21 at 14:15
  • It's been updated on `react-router-dom` v6 to `useNavigate()`. Use as follows: `const navigate = useNavigate(); navigate("/home");` – Seiwon Park Apr 06 '23 at 09:08