Call function from another React component

My first component looks like this:

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 the 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 similar, but this doesn't make the job:

import { Welcome } from './Welcome'

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

      

I would like to get a random array element hellos

printed in Life.

+3


source to share


1 answer


There are several ways to achieve this:

You can do this by creating a 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 component you want to share with 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 by https://www.webpackbin.com/bins/-KkgrwrMGePG4ixI0EKd

Another way is to just define your sayHello function as static.

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

      

+2


source







All Articles