React Tutorial #3 - Get Your Props Up
With the understanding of JSX from the previous post, we can now move on to learning more about Props!
Now that we have understood JSX, we know that we can describe our UI in JSX, in a single component if you like.
const todos = [
{
id: 1,
content: "Clean the dishes",
},
{
id: 2,
content: "Buy groceries",
},
{
id: 3,
content: "Write a React tutorial",
},
];
const App = () => {
// we want to create a simple todo listing
return (
<ul>
{todos.map((todo) => (
<li
key={todo.id}
onClick={() => console.log(`clicked on todo ${todo.content}`)}
>
{todo.content}
</li>
))}
</ul>
);
};
In this example, the todo items in an unordered list is simple enough to describe in a single component. However, like functions in JavaScript, components can be extracted into smaller components to simplify the render logic and facilitate easier testing.
The example above can be modified to below.
/**
* ... (todos declaration omited for brevity)
*/
const TodoItem = () => {
return (
<li onClick={() => console.log(`clicked on todo todo item`)}>todo item</li>
);
};
const App = () => {
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} />
))}
</ul>
);
};
With this code, we have successfully extracted the todo item from the App
component, but every TodoItem
now renders with the inner text todo item
instead of the original text declared above.
As some of you may notice, I have been assigning some variables to the li
in the first example. That is props
that we're learning about today, and we can pass values down to the children by using props.
In order to properly describe the TodoItem
component, we can declare it as below using props
.
/**
* ... (todos declaration omited for brevity)
*/
type TodoItemProps = {
content: string,
onClick: () => void,
};
const TodoItem = (props: TodoItemProps) => (
<li onClick={props.onClick}>{props.content}</li>
);
const App = () => {
return (
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
content={todo.content}
onClick={() => console.log(`clicked on todo ${todo.content}`)}
/>
))}
</ul>
);
};
Now, we should be able to see the same result as our first example.
With props
we can pass down values to child component and decouple the children UI logic from whatever complex logic we have on our parent component.
Conclusion
We have learned what props are and how it can benefit us when designing our React components. If you have doubts you can also reach me on my socials and I will be more than happy to help you.
Hope you find this blog post helpful and in our next blog post, we will be discussing about React Hooks. See you guys on the next blog post!