// 1. find a piece of DOM:
const taco = document.getElementById("taco")
// 2. Add an event listener to that piece
// 3. Give type and callback to the event listener:
taco.addEventListener("click", () => {
console.log("taco has been clicked")
})
function taco(){
return(
<button onClick = { () => {
console.log("taco btn got clicked")
}}> TACO </button>
)
}
<button onClick={() => {
console.log("taco clicked")
}}> TACO </button>
<ButtonComponent onClick = { () => {
console.log(" why is this not working? ")
}}> TACO </ButtonComponent>```
function counter() {
const handleClick = (event) => {
console.log(event)
}
return (
<button onClick = {handleClick}> counter + </button>
)
}
In React, a synthetic event is an abstraction over native browser events. Instead of directly working with the native event object provided by the browser (e.g. click, submit), React creates its own “synthetic” event object.
In React, event handling attributes are named using the “on” keyword as a convention. This makes it easier to distinguish event handlers from other attributes and helps maintain a consistent naming pattern.
State is private data to the component where it’s defined.
We can use this state to make our component more dynamic, trigger re-renders, and perform DOM manipulation based on how our state is manipulated.
Props are passed down from parents to children and remain static.
Meanwhile, values stored in state are meant to change, especially as the user interacts with the DOM.
This is a key component of declarative programming in React: we tie our components to our state by integrating values in state into logic (e.g., conditional rendering). This way, changes in state eventually cause changes to the DOM.
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return <button>Count: {count}</button>;
}
useState hook from react.useState with an initial value; in this case, it is 0.const [count, setCount] = useState(0);
const countState = useState(0);
// => [initialVal, setterFunction]
const count = countState[0];
const setCount = countState[1];
// => [0, setCount]
const arr = useState(0);
// => [0, setStateFunction]
const count = arr[0];
const setCount = arr[1];
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}
Two important decisions we’ll need to start making when working in React are:
From Step 3 of Thinking in React: to decide what we need as state, ask three questions about each piece of data:
From Step 4 of Thinking in React: To decide where state should live, for each piece of state in your application:
βοΈβοΈβοΈβοΈβοΈβοΈβοΈβοΈ
πββοΈπββοΈπββοΈπββοΈπββοΈπββοΈπββοΈπββοΈ