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.
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.
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.
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))];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With