Home > Software engineering >  How do I use React Router Dom to navigate to a new page as a result of a Switch Case?
How do I use React Router Dom to navigate to a new page as a result of a Switch Case?

Time:01-17

Essentially when a form is submitted I want the page to navigate to a different page as a result from a switch statement.

switch (real_input_value()) {
  case 'Help':
    console.log('Displaying list of available commands')
    user_input_resultsHelp()
    <Link to="/"/>
    break;
}

All the components in react-router-dom have to go into the html area and not the javascript area, so how do I navigate to a new page using javascript inside of this switch statement?

Component code:

const App = () => {

  const input_command_logic = (e) => {
    e.preventDefault();
    switch (real_input_value()) {
      case 'Help':
        console.log('Displaying list of available commands')
        user_input_resultsHelp()
        <Link to="/"/>
        break;
  }

  return()

CodePudding user response:

Since the switch statement is a form element's onSubmit callback it will need to issue an imperative navigation action. For this import and use the useNavigate hook to access the navigate function in the component, and issue the navigation action in the handler.

Example:

import { ..., useNavigate } from 'react-router-dom';

...

const MyComponent = () => {
  const navigate = useNavigate();

  ...

  submitHandler = event => {
    event.preventDefault();

    ...

    switch (real_input_value()) {
      ...

      case 'Help':
        console.log('Displaying list of available commands')
        user_input_resultsHelp()
        navigate("/");
        break;

      ...
    }

  };

  ...
  • Related