Home > other >  how to switch component in React?
how to switch component in React?

Time:02-28

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

CodePudding user response:

you can achieve redirection in multiple ways in react.

1- just use Link from react-router-dom

<Link to={"/my-route"} />

2- you can use useNavigate from react-router-dom

const navigate = useNavigate()
navigate("/my-route")

3- you can simple use state to show/hide compoenents if

const [visibleComponent, setVisibleComponent] = useState('component1')
<Component1 isVisible={visibleComponent === 'component1'} />
<Component2 isVisible={visibleComponent === 'component2'} />
<Component3 isVisible={visibleComponent === 'component3'} />

and then you can change the component based on your logic ( setVisibleComponent('component2') to show the second component and so on ...

CodePudding user response:

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