RipperNoChart
RipperNoChart

Reputation: 51

How can show and hide react components using hooks

Hy! How can i display a component if another component is visible, ex

if component 1: show component 2: hide component 3: hide

if component 2: show component 3: hide component 1: hide

(i have 10 components)

Im using react hooks, thanks

Upvotes: 3

Views: 2998

Answers (3)

Ghazi Khan
Ghazi Khan

Reputation: 26

You can keep one string value in useState which will be id for the component in this case it will be only one state value through which we will toggle display. You can see it below

function Parent() {
  const [childToDisplay, setChildToDisplay] = useState(null)
  
 return (
  <>
    <Comp1 id='comp-1' display={childToDisplay === 'comp-1'} />
    <Comp2 id='comp-2' display={childToDisplay === 'comp-2'} />
  </>
 )
}

To toggle the display you can keep button in parent component. Whenever you have to show any component you can set the correct id to state as string and it will then display child component accordingly.

This way you don't have to set multiple boolean state values for multiple child components.

Upvotes: 0

Florian Motteau
Florian Motteau

Reputation: 3714

You need to handle this in a parent component, the parent for your 10 children. This parent component should implement the logic driving the hidden/shown state for all the children.

In other words you need to lift state up.

Upvotes: 1

Pavlo Zhukov
Pavlo Zhukov

Reputation: 3337

You need to use useEffect hook to track the open state of the component which you want to sync with another component.

Next code will trigger the opening of the Comp2 component while Comp1 is opened

function Comp1({open, showAnotherChild}) {
  useEffect(() => {
    if (open) {
      showAnotherChild()
    }
  }, [open])
  if (!open) {
    return null
  }

  return // markup
}

function function Comp2({open}) {
  if (!open) {
    return null
  }

  return // markup
}

function Parent() {
  const [comp1Open, setComp1Open] = useState(false)
  const [comp2Open, setComp2Open] = useState(false)
  
 return (
  <>
    <Comp1 open={comp1Open} showAnotherChild={setComp2Open} />
    <Comp2 open={comp2Open} />
    <button onClick={() => setComp1Open(true)}>Open Comp1</button>
  </>
 )
}

Upvotes: 1

Related Questions