Home > Software engineering >  Page Navigation not working on Button Click
Page Navigation not working on Button Click

Time:11-26

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;

CodePudding user response:

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");
  }
  • Related