0

This is my sorting.js file and I am trying to access the resetArray of this file from a onClick button listener of App.js. But unable to do it. Please help.

export default class sorting extends React.Component {
 constructor() {
   super();
   this.state = {
    array: [],
   };
 }

 resetArray() {
   var array = [];
   for (let i = 0; i < 80; i++) {
      array.push(this.randomNumber(10, 350));
   }
   this.setState({ array });
 }
}

This is my App.js file

import React from 'react';
import Sorting from './sorting/sorting.js';

class App extends React.Component {
  render() {
  return (
    <div>
      <Sorting />
      <button onClick={() => this.resetArray()}>
    </div>
  )
  }
}
  • 3
    If you want `App` to be able to call some `resetArray` callback then the callback should be declared in `App` and passed to the button. If you want the callback to update *some* array in another component, then the array should also be declared in `App` and passed to the component. See [Lifting State Up](https://reactjs.org/docs/lifting-state-up.html). Basically state & behavior need to reside in the closest common ancestor to the components that need to display or update it. – Drew Reese Sep 30 '20 at 21:30
  • https://stackoverflow.com/questions/37949981/call-child-method-from-parent – Khayankhyarvaa Turmandakh Oct 01 '20 at 02:10
  • Wow thanks for the help. – Jayesh Shukla Oct 01 '20 at 17:31

1 Answers1

0

You need to bring your state up in the hierarchy, in this case, array to your App's state instead of Sorting. Also, you can declare your function in the App.js and pass it as a prop to Sorting.js and call it from there.

I have refactored your code to make it work.

Codesandbox with your refactored code (check console)

Lakshya
  • 684
  • 6
  • 10
  • Thanks for your help I needed that, how to get a good grasp of all this state class components and callback any reference... as I am unable to get the information online. – Jayesh Shukla Oct 01 '20 at 17:33
  • I think react's documentation is very well written, so you can refer to that and try building your own project from the scratch. This can be a good starting point on [how to think in react](https://reactjs.org/docs/thinking-in-react.html) You can also follow along with tutorials available on Youtube, most of them are good enough to get you started. All the best! – Lakshya Oct 03 '20 at 00:15