Search code examples
reactjscomponentsstatereact-functional-component

Swapping ReactJS functional component on state change


I am new to react and struggling to change the state of a component, and on the change replace the contents.

I have the following:

function App() {

 const [page, setPage] = React.useState('list');

 switch(page) {
  case 'A':
   return(
   <body> 
    <Home />
    <A />
   </body>
  )
  case 'B':
  return(
   <body> 
    <Home />
    <B />
   </body>
  )
 }
}

function A() {
 
 return (
  <div>
   <div onClick={() => setPage('B')}>GoToB</div>
  </div>
 )
}

function B() {
    return (
       <div>test</div>
    )
}

There is a separate Home component that displays properly. How do I correctly call the setPage function to change the state so that the switch case is triggered and changes out the component?


Solution

  • function App() {
    
     const [page, setPage] = React.useState('list');
    
    function A({setPage}) {
     
     return (
      <div>
       <div onClick={() => setPage('compsci')}>GoToB</div>
      </div>
     )
    }
    
    function B({setPage}) {
        return (
          <div>
       <div onClick={() => setPage('list')}>GoToB</div>
      </div>
        )
    }
    
     switch(page) {
      case 'list':
       return(
       <body> 
        <Home />
        <A setPage={setPage}/>
       </body>
      )
      case 'compsci':
      return(
       <body> 
        <Home />
        <B setPage={setPage} />
       </body>
      )
     }
    }