Tony
Tony

Reputation: 77

How can I use state to render form components in React?

I'm building two form components and I want to display a two buttons onPage load, where the click on the first button takes to the first form or the click on the second button takes to the second form component. I've tried to use useNavigate/useHistory but i'm still on same page.



function App() {

  const navigate = useNavigate()
  

  return (
    
      <div className="app">
        <Header />
        <button onClick={()=> navigate("/main")}>Click me!</button>
        <button onClick={()=> navigate("/main2")}>Click me!</button>
        <Routes>
          <Route exact path="/main" component={Main}/>
          <Route exact path="/main2" component={Main2}/>
       </Routes>

      </div>
    
  );
}

export default App;


How can I use react-router or state to display the component when a each button is clicked? I would appreciate any help

Upvotes: 0

Views: 41

Answers (1)

Tanishq Vyas
Tanishq Vyas

Reputation: 1689

Assuming that you have react-router-dom v6 since you have used <Routes></Routes>. You must write the code in the following manner under the assumption that you have included <Router> to wrap your application in index.js.

function App() {

  const navigate = useNavigate()
  

  return (
    
      <div className="app">
        <Header />
        <button onClick={()=> navigate("/main")}>Click me!</button>
        <button onClick={()=> navigate("/main2")}>Click me!</button>
        <Routes>
          <Route path="/main" element={<Main />}/>
          <Route path="/main2" element={<Main2 />}/>
       </Routes>

      </div>
    
  );
}

export default App;

Here, after clicking the first button, it will route you to /main which will serve the <Main /> component. The second button will route to /main2 and will serve the <Main2 /> component.

In version 6, there is no longer the need to write exact since the default behavior is to match the exact route. Also there are some interface changes where the component attribute is changed to element and it now takes the JSX as value and not the object itself.

Upvotes: 1

Related Questions