how to pass this 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: callback in react
import React, { useCallback } from 'react';
function MyComponent() {
const handleClick = useCallback(() => { console.log('Clicked!'); }, []);
}
Example 3: pass params react js
App.js -> ColorPicker (Components/ColorPicker.js)
import ColorPicker from './Component/ColorPicker';
class App extends Component {
constructor(props) {
super(props);
this.state = {
color: 'red',
};
}
render() {
return (
<div className="col">
<ColorPicker color={ this.state.color } />
</div>
)
}
}export default App;
import React, { PureComponent } from 'react';
class ColorPicker extends PureComponent {
constructor(props) {
super(props);
this.state = {
colors: ['red', 'green', 'blue', 'yellow', 'purple'],
};
}
render() {
var elementColors = this.state.colors.map((c, index) => {
return <span key={ index }
className={ this.props.color === c ? 'active squad ml-10' : 'squad ml-10'}
}
>
</span>
});
}
export default ColorPicker;
ColorPicker (Components/ColorPicker.js) -> App.js
import React, { PureComponent } from 'react';
class ColorPicker extends PureComponent {
constructor(props) {
super(props);
this.state = {
colors: ['red', 'green', 'blue', 'yellow', 'purple'],
};
}
setActiveColor = (c) => {
this.props.onReceiverColor(c);
}
render() {
var elementColors = this.state.colors.map((c, index) => {
return <span key={ index }
onClick={ () => this.setActiveColor(c) }
>
</span>
});
}
export default ColorPicker;
import React, { Component } from 'react';
import ColorPicker from './Component/ColorPicker';
class App extends Component {
onSetColor(c) {
alert(c);
}
render() {
return (
<ColorPicker onReceiverColor={ this.onSetColor } />
);
}
}export default App;