1import React from 'react';
2
3const ExampleComponent = () => {
4
5 function sayHello(name) {
6 alert(`hello, ${name}`);
7 }
8
9 return (
10 <button onClick={() => sayHello('James')}>Greet</button>
11 );
12}
13
14export default ExampleComponent;
1class Foo extends Component {
2 constructor(props) {
3 super(props);
4 this.handleClick = this.handleClick.bind(this);
5 }
6 handleClick() {
7 console.log('Click happened');
8 }
9 render() {
10 return <button onClick={this.handleClick}>Click Me</button>;
11 }
12}
1import React, { useCallback } from 'react';
2
3function MyComponent() {
4 // handleClick is the same function object
5 const handleClick = useCallback(() => { console.log('Clicked!'); }, []);
6 // ...
7}
1import React, {useState} from 'react';
2
3// Create a callback in the probs, in this case we call it 'callback'
4function newCallback(callback) {
5 callback('This can be any value you want to return')
6}
7
8const Callback = () => {
9
10const [callbackData, setCallbackData] = useState('')
11
12// Do something with callback (in this case, we display it on screen)
13function actionAferCallback (callback) {
14 setCallbackData(callback)
15}
16
17// Function that asks for a callback from the newCallback function, then parses the value to actionAferCallback
18function requestCallback() {
19 newCallback(actionAferCallback)
20}
21
22 return(
23 <div>
24 {/* A button to activate callback */}
25 <button onClick={() => {requestCallback()}}>Request Callback</button>
26 {callbackData}
27 </div>
28 )
29}
30
31export default Callback;