callback react 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: react button onclick
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;
Example 3: callback in react
import React, { useCallback } from 'react';
function MyComponent() {
const handleClick = useCallback(() => { console.log('Clicked!'); }, []);
}
Example 4: react button onclick
<button onClick={sayHello}>Click</button>
Example 5: 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;