CPRG-306 Week 3
Components and Props
Agenda
- JavaScript: Objects, Destructuring, JSON
- React Props
- Tailwind CSS: typography, colours, spacing
The goal is to learn how to pass data to components using props.
Objects
- Objects are a way to store data in key-value pairs
- Keys are strings that identify the value
- Values are the data associated with the key
- Objects can contain other objects
Object Example
let person = {
name: "Diane",
age: 25,
isStudent: true,
address: {
street: "123 Main St",
city: "Calgary",
province: "AB",
},
};
Object Properties
- Access properties using dot notation
let name = person.name; // Diane
let city = person.address.city; // Calgary
person.isStudent = false; // change value
JSON
- JavaScript Object Notation
- A way to store and exchange data
- Similar to objects, but with a few differences
- Keys must be quoted strings and values must be one of the following: string, number, object, array, boolean, null
JSON Example
{
"name": "Diane",
"age": 25,
"isStudent": true,
"address": {
"street": "123 Main St",
"city": "Calgary",
"province": "AB"
}
}
Typography
text-
classes for text stylingfont-
classes for font styling
<div>
<h1 className="text-2xl font-bold font-serif">Big Title!</h1>
<p className="text-center">Centered text</p>
</div>
Colours
text-
classes for text colourbg-
classes for background colour
<div className="bg-blue-900">
Dark blue background
<h1 className="text-red-300">Light red text</h1>
</div>
Spacing
p-
classes for paddingm-
classes for margin
<article>
<div className="p-4">Padding of 1rem or 16px</div>
<div className="m-4">Margin of 1rem or 16px</div>
<h1 className="pl-1 mt-3">Left padding of 4px and top margin of 12px</h1>
<h2 className="px-2 my-5">
Horizontal padding of 8px and vertical margin of 20px
</h2>
</article>
Object Destructuring
- Destructuring is a way to extract properties from an object
- Destructuring is useful when passing data to components
let { name, age } = person;
console.log(name); // Diane
console.log(age); // 25
React Props
- a way to pass data to components
- accessed using
props
object containing all the properties passed to the component
Props Example
function Page() {
return (
<main>
<Person name="Diane" age="25" />
<Person name="Zach" age="21" />
</main>);
}
function Person(props) {
return (
<div>
<h1>{props.name}</h1>
<p>Age: {props.age} years old</p>
</div>);
}
Demo
- Use objects to store data
- Display the data
- Add some styling with Tailwind CSS
- Implement a component that uses props
- Use destructuring to access props