0

This is my Tools.js

export default class Tools extends React.Component {
    show() {
        console.log(1)
    }
}

And this is my App.js

export default class App extends React.Component {
    componentDidMount() {
        Tools->show(); // ???
    }
    
    render() {
        return (
            <div className="App">
                <Loading />
                <Header />
            </div>
        );
    }
}

I want call show() function in componentDidMount() of App

How I can call function from another class into App?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Parsa Nikoo
  • 125
  • 3
  • 11
  • You'd import your Tool class at the top of the App class file, and then you'd be able to call `show()` – Joshua Terrill Jun 16 '21 at 18:21
  • @JoshuaTerrill i import this: `import Tools from './components/class/Tools';` – Parsa Nikoo Jun 16 '21 at 18:23
  • @MattU yes i saw this. but i cant understand it – Parsa Nikoo Jun 16 '21 at 18:26
  • Tools.prototype.show() - but you should never do this !. Just define common function in separate file – Robert Jun 16 '21 at 18:26
  • @Robert this code work fine. but why i dont use it? – Parsa Nikoo Jun 16 '21 at 18:27
  • 1
    Because your code will embroiled. Common practice is to separate each common functionality in separate function/class in it's own file. In near function you will forget that this function is used in other components and you will adjust it to this Tools component. This is just really bad practice. – Robert Jun 16 '21 at 18:31
  • [sanbox - check c2 component](https://codesandbox.io/s/boring-hypatia-nrbvu?file=/src/C2.js) – Robert Jun 16 '21 at 18:38
  • It would be much simpler for you to leverage functional programming to implement composition vs inheritance, as explained here: https://reactjs.org/docs/composition-vs-inheritance.html – AGE Jun 16 '21 at 18:38
  • You can do this from technical point of view. And you should not from an architectural point of view – Robert Jun 16 '21 at 18:39

1 Answers1

1

Since your importing a class you need to instantiate it with new then use your show method.

In your App.js:

import {Tools} from 'Tools.js';

const myTool = new Tools();

export default class App extends React.Component {
componentDidMount() {
    myTool.show();
}

render() {
    return (
        <div className="App">
            <Loading />
            <Header />
        </div>
    );
}

}

Colin Rosati
  • 303
  • 2
  • 14