DEV Community

Syed Hasibur Rahman
Syed Hasibur Rahman

Posted on

Props, PropTypes, JSX

Props:
React allows us to pass information to components using things called props (short for properties). Because React comprises several components, props make it possible to share the same data across the components that need them. It makes use of one-directional data flow (parent-to-child components). However, with a callback function, it’s possible to pass props back from a child to a parent component.
These data can come in different forms: numbers, strings, arrays, functions, objects, etc. We can pass props to any component, just as we can declare attributes in any HTML tag. Take a look at the code below:

In this snippet, we are passing a prop named posts to a component named PostList. This prop has a value of {postsList} Let’s break down how to access and pass data.

PropTypes:
PropTypes are a mechanism to ensure that components use the correct data type and pass the right data, and that components use the right type of props, and that receiving components receive the right type of props.

We can think of it like a fruits s being delivered to a fruit store. The pet store doesn’t want pigs, lions, frogs, or geckos — it wants puppies. PropTypes ensure that the correct data type (fruits) is delivered to the pet store, and not some other kind of fruit.

In the section above, we saw how to pass information to any component using props. We passed props directly as an attribute to the component, and we also passed props from outside of the component and used them in that component. But we didn’t check what type of values we are getting in our component through props or that everything still works.

It’s totally upon us whether to validate the data we get in a component through props. But in a complex application, it is always a good practice to validate that data.

JSX:
JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together.
Take a look:
const jsx =

This is JSX

This is simple JSX code in React. But the browser does not understand this JSX because it's not valid JavaScript code. This is because we're assigning an HTML tag to a variable that is not a string but just HTML code.

So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a JavaScript compiler/transpiler.

You can set up your own babel configuration using Webpack as I show in this article. Or you can use create-react-app which internally uses Babel for the JSX to JavaScript conversion.

Top comments (0)