react callback
import React from 'react';
const ExampleComponent = () => {
function sayHello(name) {
alert(`hello, ${name}`);
}
return (
<button onClick={() => sayHello('James')}>Greet</button>
);
}
export default ExampleComponent;class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.sayHello = this.sayHello.bind(this);
}
sayHello() {
alert('Hello!');
}
return (
<button onClick={this.sayHello}>
Click me!
</button>
);
}
export default App;import React, { useCallback } from 'react';
function MyComponent() {
// handleClick is the same function object
const handleClick = useCallback(() => { console.log('Clicked!'); }, []);
// ...
}import React, {useState} from 'react';
// Create a callback in the probs, in this case we call it 'callback'
function newCallback(callback) {
callback('This can be any value you want to return')
}
const Callback = () => {
const [callbackData, setCallbackData] = useState('')
// Do something with callback (in this case, we display it on screen)
function actionAferCallback (callback) {
setCallbackData(callback)
}
// Function that asks for a callback from the newCallback function, then parses the value to actionAferCallback
function requestCallback() {
newCallback(actionAferCallback)
}
return(
<div>
{/* A button to activate callback */}
<button onClick={() => {requestCallback()}}>Request Callback</button>
{callbackData}
</div>
)
}
export default Callback;