How can I render second child component and disappear first child component?

Viewed 58

I want to develop a parent component in which child component will be rendered by default, it has check box, upon clicking on that check box it will render another child component and that first child component should disappear.

2 Answers

set a state with the initial value true a when change the check box set it to false and write condition to state? <First/>: <Second/>

You can use an <input type="checkbox"> element to toggle a boolean state value. Then use that state value to determine which child component is rendered. Here's an example which will render Component A when checked is false, and will render Component B when checked is true, using the conditional (ternary) operator ?:

body { font-family: sans-serif; } label { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
<div id="root"></div><script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.19.0/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

const {useState} = React;

function ComponentA () {
  return (<div>Component A</div>);
}

function ComponentB () {
  return (<div>Component B</div>);
}

function App () {
  const [checked, setChecked] = useState(false);

  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={checked}
          onChange={ev => setChecked(ev.target.checked)}
        />
        <span>Toggle component</span>
      </label>
      {
        checked
          ? <ComponentB />
          : <ComponentA />
      }
    </div>
  );
}

const reactRoot = ReactDOM.createRoot(document.getElementById('root'));

reactRoot.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

</script>

Related