I want to access a method from outside the component. I found several tutorials that should allow me to call methods by window.PathfindingVisualizer.resetGrid(), but I'm getting an error saying resetGrid is not a function
example I tried to follow: https://brettdewoody.com/accessing-component-methods-and-state-from-outside-react/
my App.js
function App() {
return (
<div className="App">
<PathfindingVisualizer
ref={(PathfindingVisualizer) => {window.PathfindingVisualizer = PathfindingVisualizer}}
/>
</div>
);
}
export default App;
my PathfindingVisualizer.js:
export default class PathfindingVisualizer extends React.Component {
constructor(props) {
super(props)
this.state = {
grid: [],
mouseLeftDown: false,
};
const mouseStrat = null;
}
resetGrid() {
//do stuff
}
componentDidMount() {
this.resetGrid();
this.mouseStrat = new MouseStrat(); //Object I want to call functions from
}
}
And I want to call the resetGrid() and setState from outside of react with:
//errors resetGrid and setState is not a function
export class MouseStrat {
handleMouseDown(row, col) {
window.PathfindingVisualizer.resetGrid();
}
}
What am I doing wrong?
So if I understand correctly, you have a component with a variable that is a class that contains a function that calls a function that's already in the component. This seems quite complicated, and there may be a simpler solution to what you're trying to achieve.
Here's an alternative solution. Make resetGrid function a property of the MouseStrat class:
export class MouseStrat {
constructor(resetGrid) {
this.resetGrid = resetGrid;
}
handleMouseDown(row, col) {
this.resetGrid();
}
}
Then, in PathfindingVisualizer:
export default class PathfindingVisualizer extends React.Component {
constructor(props) {
super(props)
this.state = {
grid: [],
mouseLeftDown: false,
mouseStrat: null // You had this as a variable before
};
this.resetGrid = this.resetGrid.bind(this); // You must bind your function for it to work properly in a React component
}
function resetGrid () {
//do stuff
}
componentDidMount() {
this.resetGrid();
this.mouseStrat = new MouseStrat(this.resetGrid); // Now you pass the function as an argument
}
}
Where are you calling these functions? If they are being run too early window.PathfindingVisualizer may not have a value yet. You may want to run them in a hook like componentDidUpdate.