How to use events and props in ReactJS.
Firstly, we will discuss on how event
works in ReactJS, and how you can add it to your application.
Just like HTML DOM events, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc.
React events are written in camel Case syntax examples are:
onClick
instead of onclick
.
React event handlers are written inside curly braces:
onClick={shoot}
instead of onclick="shoot()"
.
Code Sample:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
You can also pass an argument to an event handler, by using arrow function.
Code Sample:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Event handlers have access to the React event that triggered the function.
Code Sample:
function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Now, let's discuss how props
works.
Props are arguments passed into React components. Props are always passed to components via HTML attributes.
Note: React Props are like function arguments in JavaScript and attributes in HTML, and to send props into a component, use the same syntax as HTML attributes like this: const myelement = <Car brand="Ford" />;
. Component receives the argument as a props object.
Example:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
Props in React are also how you pass data from one component to another, as parameters.
Code Sample:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
If you have a variable to send, and not a string as in the example above, you just put the variable name inside curly brackets:
Code Sample:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
You can also do it like the code sample below, if it was an object:
function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));