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?

9
  • You'd import your Tool class at the top of the App class file, and then you'd be able to call show() Commented Jun 16, 2021 at 18:21
  • @JoshuaTerrill i import this: import Tools from './components/class/Tools'; Commented Jun 16, 2021 at 18:23
  • @MattU yes i saw this. but i cant understand it Commented Jun 16, 2021 at 18:26
  • Tools.prototype.show() - but you should never do this !. Just define common function in separate file Commented Jun 16, 2021 at 18:26
  • 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. Commented Jun 16, 2021 at 18:31

1 Answer 1

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>
    );
}

}

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

1 Comment

Thank you. Can I access direct to function like php? Tools::show(); ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.