0

I have a two child components and I want a button in one of them to toggle (on/off) the html in another. I have watched tutorials on lifting state up, and communication between components but most of it has to do with moving data. I want to manipulate a component from another. I would like the achieve this using useState, and without useContext if possible. Thanks!

THE PARENT

import React from "react";

function App() {
  return (
    <div>
      <AppProvider>
        <ComponentOne/>
        <Slideshow />
        <ComponentTwo/ >
      </AppProvider>
    </div>
  );

} 

CHILD 1




export default function ComponentOne() {
 

  return (
    <div>
      <button>The button that toggles</button>
    </div>
  );
}

CHILD 2




export default function ComponentTwo() {
 

  return (
    <div>
      <div>The content that hides/shows</div>
    </div>
  );
}

1 Answer 1

2

You need to use state to toggle the values. Pass the state to the ComponentTwo as props and pass the state updater function as the callback function to the ComponentOne as a prop.

import React , { useState, useCallback } from 'react';

function ComponentOne({ onToggle}) {
  return (
    <div>
      <button onClick={onToggle}>The button that toggles</button>
    </div>
  );
}

function ComponentTwo({show}) {

  return (
    <div>
     {show && <div>The content that hides/shows</div>} 
    </div>
  );
}

export default function App() {
  const [show, setShow ] = useState(true);

  const handleToggle = useCallback(() => setShow(prevShow => !prevShow),[])

  return (
    <div className="App">
      <ComponentOne onToggle={handleToggle} />
      <ComponentTwo show={show} />
    </div>
  );
}

Refer

useState

useCallback

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this answers it! Can i ask why you have useCallback? I am unfamiliar with that hook. Is there an alternative way without useCallback using only useState? and if so, why not just do that?
The reason to use , useCallback here is everytime when there is a state change you re-run the function App due to this you will be creating the handleToggle function each time and passing at as props to the ComponentOne . Now consider ComponentOne renders a table along with the button. Now because the reference of handleToggle changes each time the component will keep re-rendering which results in re-rendering the table each time . But your intention is to only re-render ComponentTwo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.