Using props in React
Table of Contents
See https://github.com/explorer436/programming-playground/tree/main/react-playground/07-using-props
parameters
const someFunc = (param1, param2) => {
console.log(param1, param2);
};
arguments
someFunc('job', 'developer');
By default, every component gets a props
parameter. React injects that.
Using props
Essentially, we pass in data into the smaller functions using props
function BookList() {
return (
<section className="booklist">
<Book author={author} title={title} img={img} />
<Book title={title} img={img} />
</section>
);
}
const Book = (props) => {
console.log(props);
return (
<article className="book">
<img src={props.img} alt={props.title} />
<h2>{props.title}</h2>
<h4>{props.author} </h4>
</article>
);
};
Making props dynamic
const firstBook = {
author: "Ariel Lawhon",
title: "The Frozen River: A GMA Book Club Pick: A Novel",
img: "./images/91ulu+khYLL._AC_UL600_SR600,400_.jpg",
};
const secondBook = {
author: "James Clear",
title: "Atomic Habits",
img: "https://images-na.ssl-images-amazon.com/images/I/81wgcld4wxL._AC_UL900_SR900,600_.jpg",
};
function BookList() {
return (
<section className="booklist">
<Book
author={firstBook.author}
title={firstBook.title}
img={firstBook.img}
/>
<Book
author={secondBook.author}
title={secondBook.title}
img={secondBook.img}
/>
</section>
);
}
const Book = (props) => {
console.log(props);
return (
<article className="book">
<img src={props.img} alt={props.title} />
<h2>{props.title}</h2>
<h4>{props.author} </h4>
</article>
);
};
Accessing props in a function
We can use destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Children props
- everything we render between component tags
- during the course we will mostly use it Context API
- special prop, has to be “children”
- can place anywhere in JSX