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.
sayHellois a method of an instance, not a static function. You would have to create an instance ofWelcomevia creating aWelcomeelement and using refs or making it static. Anyways, this seems like the wrong decision.