shalinds
shalinds

Reputation: 73

Call a method in a React component form another Component using Hooks

I want to clear user's input data in a one component from button click event in another component. Component structure looks like bellow :

                         Search (contains Reset button)
                           |
                          Tabs
                           |
                   ------------------
                   |       |       |
                Student   Subject  Lecturer > (These components contains their own Rest fucntions)

HTML elements in the selected tab should clear data when Reset button is clicked. Each tab component(Student, Subject, Lecturer) contains related UseStates and Reset function(ResetStudent(), ResetSubject()).

How can I achieve this using ReactHooks ?

<Search> 
 <Tabs/>
<button type="button">Search</button>
<button type="button">Reset</button>
</Search>

Sample code look like below :

function Search() {
  
  return (
    <div className="App">
       <TabsComponent/>
      <button type="button">Search</button>
      <button type="button">Reset</button>
    </div>
  );
}

export default Search;
function TabsComponent() {
  
  return (
    <div >
       <Student/>
       <Subject/>
    </div>
  );
}

export default TabsComponent;
function Student() {
  
  return (
    <div >
        <label for="fname">First name:</label>
        <input type="text" id="fname" name="fname">
    </div>
  );
}

export default Student;

Upvotes: 1

Views: 9380

Answers (1)

EvanMorrison
EvanMorrison

Reputation: 1217

There's several ways to do it that are all valid, here's a CodeSandbox showing a fairly basic way just with useState and useEffect.

The idea is fairly simple. It just takes one state prop to pass down from Search to each of the three tab components, a boolean reset value. The rest is just adding useEffect to watch for changes in reset and responding accordingly.

Here's a working example:

Edit proud-surf-31821

Upvotes: 4

Related Questions