React.callback code example
Example 1: react bind function to component
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>;
}
}
Example 2: callback in react
import React, { useCallback } from 'react';
function MyComponent() {
const handleClick = useCallback(() => { console.log('Clicked!'); }, []);
}
Example 3: react callback
import React, {useState} from 'react';
function newCallback(callback) {
callback('This can be any value you want to return')
}
const Callback = () => {
const [callbackData, setCallbackData] = useState('')
function actionAferCallback (callback) {
setCallbackData(callback)
}
function requestCallback() {
newCallback(actionAferCallback)
}
return(
<div>
{}
<button onClick={() => {requestCallback()}}>Request Callback</button>
{callbackData}
</div>
)
}
export default Callback;