binding in react code example
Example 1: react onclick parameter
import React from 'react';
const ExampleComponent = () => {
function sayHello(name) {
alert(`hello, ${name}`);
}
return (
<button onClick={() => sayHello('James')}>Greet</button>
);
}
export default ExampleComponent;
Example 2: 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 3: react button onclick
<button onClick={sayHello}>Click</button>
Example 4: two way binding react
class App extends React.Component {
constructor() {
super();
this.state = {value : ''}
}
handleChange = (e) =>{
this.setState({value: e.target.value});
}
render() {
return (
<div>
<input type="text" value={this.state.value} onChange={this.handleChange}/>
<div>{this.state.value}</div>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));