Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function from another React component

Tags:

reactjs

My first component is as follow:

const hellos = ['Hola', 'Salut', 'Hallo', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa']

export class Welcome extends Component {

    constructor(props) {
        super(props);
        this.state = {
            errors: []
        };
    }

    sayHello = function() {
        return hellos[Math.floor((Math.random()*hellos.length))];
    }

    render() {
        return (
            <div className="Welcome">

            </div>
        );
    }
}

I want to be able to call sayHello() from another component. All answers I've seen so far talk about parent and child relationships but in this case the two components don't have any relationship. I thought of something like this but it doesn't do the job:

import { Welcome } from './Welcome'

export const Life = () => (
    <div className="Life">
      <p>{ Welcome.sayHello() }</p>
    </div>
)

I would like to get a random element of the hellos array printed in Life.

like image 887
ocram Avatar asked May 21 '17 20:05

ocram


People also ask

How do you pass data from one functional component to another React?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

How do you call a function from another function in React native?

To call a function, you can either pass its name and arguments to User. callFunction() or call the function as if it was a method on the User.


1 Answers

There are a number of ways you could achieve this:

You can do this by creating the sayHello function and using it simply as a named-function.

hello.js

const hellos = ['Hola', 'Salut', 'Hallo', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa'];

const sayHello = function() {
    return hellos[Math.floor((Math.random()*hellos.length))];
};

export { sayHello };

Then you can import into which ever component you wish to share the functionality:

import { sayHello } from './hello';

class CompA extends React.Component {
    render() {
        return <span>{sayHello()}</span>;
    }
}

class CompB extends React.Component {
    render() {
        return <span>{sayHello()}</span>;
    }
}

render(<span>
        <CompA />
        <CompB />
    </span>, document.querySelector('#app'));

Created a https://www.webpackbin.com/bins/-KkgrwrMGePG4ixI0EKd

Another way, is to simply define your sayHello Function as static.

static sayHello() {
    return hellos[Math.floor((Math.random()*hellos.length))];
}
like image 180
user2340824 Avatar answered Oct 09 '22 22:10

user2340824