Home > Software design >  How do I redirct to another component in react if I use class component
How do I redirct to another component in react if I use class component

Time:10-16

I am new to react about 3 days and I am wondering how to redirect to another componet when some condtion became true.

I am using class component which mean is the syntax as below

class LanguageOptions extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            'changed': false
        }
    }

    renderLngOptions() {
        return getLanguageOptions().reduce((rs, op) => {
            rs.push(
                <option key={op}>
                    {op}
                </option>
            )
            return rs
        }, [])
    }

    markTheStateAsNotChange() {
        this.setState((state) => {
            state.changed = false
            return state
        })

        return <Navigate to="/" replace={true} />
    }

    changeLng = (e) => {
        const options = e.target.options
        const language = options[options.selectedIndex].label
        change(language)
        this.setState((state) => {
            state.changed = true
            return state
        })
    }

    render() {
        return <div className="control has-icons-left">
            <div className="select is-primary">
                <select onChange={this.changeLng}>
                    {this.renderLngOptions()}
                </select>
            </div>
            <div className="icon is-small is-left">
                <i className="fa-solid fa-language"></i>
            </div>
        </div>
    }
}

I know how to redirect to another with functional component but in class component I am failed to find any useful resource to figure out this

What I want to do ? when the state changed is true first change the value to false then redirect to '/'

How did I defined the routers ?

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <BrowserRouter>
    <Routes>
      <Route path='/' element={<Board
        globalState={globalState}
      />}>
        <Route index element={<Board
          globalState={globalState}
        />}></Route>

        <Route path='parentalSettings' element={
          <PasswordSetting
            globalState={globalState}
          />
        }></Route>

        <Route path='mainPage' element={
          <MainPage
            globalState={globalState}
          />
        }>
        </Route>
      </Route>
    </Routes>
  </BrowserRouter>
)

CodePudding user response:

"Navigate" is the component react-router provides and returns an element, you can use a shouldRedirect state property to inform the render method and return Navigate to redirect to the specified route.

class LanguageOptions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      changed: false,
      shouldRedirect: false // make this true when redirect should be ready
    };
  }


  markTheStateAsNotChange() {
    this.setState((state) => {
      state.changed = false;
      state.shouldRedirect=true; // should redirect at this point
      return state;
    });

    
  }

  render() {

    // redirect to the route using Navigate component
    if (this.state.shouldRedirect) {
      return <Navigate to="/" replace={true} />;
    }
    return (
      <div className="control has-icons-left">
        ...
      </div>
    );
  }
}

CodePudding user response:

setState accepts a callback function which will run after the states have been changed react documentation for setState

Update your markTheStateAsNotChange to take advantage of setState callback

markTheStateAsNotChange() {
 this.setState((state) => {
   state.changed = false
   return state
  }, () => {
    this.props.history.push("/")
   })
}

changeLng = (e) => {
  const options = e.target.options
  const language = options[options.selectedIndex].label
  change(language)
    this.setState((state) => {
      state.changed = true
       return state
     }, () => {
     // redirect where you would like to redirect
    })
}
  • Related