How to call the function from another component in React Native?
Here’s an example to call a function from another component in React Native:
Create a function, sayHello and then use it as a named-function
const hellos = ['Hola', 'Salut', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa'];
const sayHello = function() {
return hellos[Math.floor((Math.random()*hellos.length))];
};
export { sayHello };
Now, you can import into whichever component you wish to share the functionality like this:
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'));
BY Best Interview Question ON 11 Dec 2020