The goals for Phase 2:
Create a static frontend site with components and props (DOM Manipulation)
Use state and events to make your site dynamic (Event Handling)
Add side effects and data fetching to communicate with a server (Network Communication)
Instead of describing how to do something:
const h1 = document.createElement("h1");
h1.id = "main";
h1.className = "blue";
h1.textContent = "Hello!";
We can just describe what we want:
const h1 = (
<h1 id="main" className="blue">
Hello from JSX!
</h1>
);
Components are the building blocks of React. A component is a function that:
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
const Header = () => {
return (
<div>
<h3>Hello World</h3>
</div>
);
};
root.render(<Header />);
This is okay:
function Card() {
return (
<div id="card1" className="card">
<h1>hi</h1>
<p>wassup?</p>
</div>
);
}
This is NOT okay:
function card() {
return (
<h1>hi</h1>
<p>wassup?</p>
)
}
When you create components, one way to make them dynamic and reusable is by passing in props. For example, if we wanted to create several cards on our page using a Card component, we could do so like this:
function Card(props) {
return (
<div id="card1" className="card">
<h1>{props.greeting}</h1>
<p>{props.subGreeting}</p>
</div>
);
}
// Inside another component
return (
<div>
<Card greeting="hi" subGreeting="hello" />
<Card greeting="sup" subGreeting="what's up" />
</div>
);
The props argument in our Card component defines an object that React will pass to our function when it is called, and it will use whatever attributes we add to our JSX component as key-value pairs on that props object.
For example, if we were to add a console.log in the Card component above, we’d end up seeing this object:
function Card(props) {
console.log(props); // => { greeting: "hi", subGreeting: "hello" }
return (
<div id="card1" className="card">
<h1>{props.greeting}</h1>
<p>{props.subGreeting}</p>
</div>
);
}
Feel free to check out the application we’ll be building together over the next couple of weeks