how to switch component in React?

Cindy

I would like to let users to move main component after they create content and I don't what methods I need to use. I wanted to use something like history but it didn't work. I am using

  • "react": "^17.0.2",
  • "react-dom": "^17.0.2",
  • "react-router-dom": "^6.2.1",
import React, { Component } from 'react';

class CreateContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: {
        title: ''
      }
    }
  }

  handleInput = (e) => {
    this.setState({
      content : {
        ...this.state.content,
        [e.target.name]: e.target.value
      }
    })
  }

  addContent = async (e) => {
    e.preventDefault();
    console.log(JSON.stringify(this.state.title))
    try {
      const response = await fetch('http://localhost:9000/api/v1/content', {
        method: 'POST',
        body: JSON.stringify(this.state.content),
        mode:'cors',
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'application/json'
        }
      });

      if(!response.ok) {
        throw Error(response.statusText)
      }
// ******* HERE I wanted to add something like *******
      history.push('/main')
    } catch (err) {
      console.log('addContent failed -', err)
    }
  }

  render() {
    return (
      <div>
        <form onSubmit={this.addContent}>
          <input
            type="text"
            name="title"
            onChange={this.handleInput}
            value={this.state.content.title}
          />
          <input type="submit" value="submit" />
        </form>
      </div>
    )
  }
}

export default CreateContent
Sanket Shah

In React Router v6, you need to use useNavigate instead of history.push().

But, since you're using class component React Router v6 it doesn't support these hooks out of the box for the class components. That is why you are receiving the error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

But that doesn't mean you can't use it. You can recreate it using HOC:

import {
  useLocation,
  useNavigate,
  useParams
} from "react-router-dom";

function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    let location = useLocation();
    let navigate = useNavigate();
    let params = useParams();
    return (
      <Component
        {...props}
        router={{ location, navigate, params }}
      />
    );
  }

  return ComponentWithRouterProp;
}

You can now wrap and export your class-based components to withRouter HOC in the very familiar way they were from v4/v5.

After that you can use useNavigate from react-router-dom v6.

const navigate = useNavigate()
navigate("/main")

Regarding your query that you've mentioned in the comment:

So should I create a separate component to add the above code or I should add the above code for each component that I want to use history? or should I add it into App.js?

To work around this issue first, create a new component withRouter as indicated above, and then wrap CreateContent component in a withRouter function, when it is exported:

export default withRouter(CreateContent)

withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

withRouter reference in v5: https://v5.reactrouter.com/web/api/withRouter

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From

How to use switch statement inside a React component?

From Dev

How to style React Native switch component?

From Dev

How to create a label for a react native switch component?

From Dev

How to Switch component in React like an app

From Dev

How to switch component showing with React and CSS?

From Dev

Switch statement in a React component

From Dev

how to switch a particular component in home page from another page in react

From Dev

How to use React Native Switch inside a functional component?

From Dev

How to simulate press of React Native Switch component using Jest and Enzyme

From Dev

How to add text inside a Toggle Switch Component in React?

From

How to change the switch component's size in React Native?

From Dev

How to identify which switch component has loaded in react-router

From Dev

React button component with switch statement

From Dev

React Router Switch Component Matches

From Dev

Style React Native switch component

From Dev

Rendering specific component using switch case --- React

From Dev

React Router Switch not rendering specific component

From Dev

React js Material UI Switch Component in loop

From Dev

Combine two switch/case statements in React component

From Dev

React component switch animation with a loader - Glitchy

From Dev

Animated react routes not working with <Switch> component

From Dev

Switch to different component after button click with React

From Dev

How do I use react router v6 to switch between components on one parent component

From Dev

How to switch tabs from another component using react-native-scrollable-tab-view

From Dev

React JSX How can I switch component state between two objects on a timer

From Dev

How to use Switch case in React js functional component inside return efficiently by reusing?

From Dev

How to setTimout on react component

From Dev

How to return a component in React

From

How to extend a React component?

Related Related

  1. 1

    How to use switch statement inside a React component?

  2. 2

    How to style React Native switch component?

  3. 3

    How to create a label for a react native switch component?

  4. 4

    How to Switch component in React like an app

  5. 5

    How to switch component showing with React and CSS?

  6. 6

    Switch statement in a React component

  7. 7

    how to switch a particular component in home page from another page in react

  8. 8

    How to use React Native Switch inside a functional component?

  9. 9

    How to simulate press of React Native Switch component using Jest and Enzyme

  10. 10

    How to add text inside a Toggle Switch Component in React?

  11. 11

    How to change the switch component's size in React Native?

  12. 12

    How to identify which switch component has loaded in react-router

  13. 13

    React button component with switch statement

  14. 14

    React Router Switch Component Matches

  15. 15

    Style React Native switch component

  16. 16

    Rendering specific component using switch case --- React

  17. 17

    React Router Switch not rendering specific component

  18. 18

    React js Material UI Switch Component in loop

  19. 19

    Combine two switch/case statements in React component

  20. 20

    React component switch animation with a loader - Glitchy

  21. 21

    Animated react routes not working with <Switch> component

  22. 22

    Switch to different component after button click with React

  23. 23

    How do I use react router v6 to switch between components on one parent component

  24. 24

    How to switch tabs from another component using react-native-scrollable-tab-view

  25. 25

    React JSX How can I switch component state between two objects on a timer

  26. 26

    How to use Switch case in React js functional component inside return efficiently by reusing?

  27. 27

    How to setTimout on react component

  28. 28

    How to return a component in React

  29. 29

    How to extend a React component?

HotTag

Archive