🎓 A1Learner
🔍
0 of 50 lessons completed

Switching Components

Switching components swaps one whole component for another. A state value picks which component renders.

Pick the home view

The home view shows the Home component.

function Home() { return <h1>Home</h1>; }
function About() { return <h1>About</h1>; }
const view = 'home';
return view === 'home' ? <Home /> : <About />;

Pick the about view

The about view shows the About component.

function Home() { return <h1>Home</h1>; }
function About() { return <h1>About</h1>; }
const view = 'about';
return view === 'home' ? <Home /> : <About />;

Example

import { useState } from 'react';

function Home() {
  return <h1>Home</h1>;
}

function About() {
  return <h1>About</h1>;
}

export default function App() {
  const [view, setView] = useState('home');
  return (
    <div>
      <button onClick={() => setView('home')}>Home</button>
      <button onClick={() => setView('about')}>About</button>
      {view === 'home' ? <Home /> : <About />}
    </div>
  );
}

Key points

  • A state value names the current view.
  • A condition picks the component that matches the value.
  • Each component keeps its own JSX.
  • A button changes the state value.
  • The page updates when the state value changes.

In this example, Home and About are small components. The view state value starts as home. The ternary expression renders Home when view is home. A click sets view to about. The next render shows About instead.

Note

Only the picked component renders, so the others stay hidden.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What picks which component renders when switching components?