This post is for developers who just dipped their hands into React Js. Before we dive in, I'd be doing a very quick refresher course on functions in JavaScript. In very simple terms,
Functions in JavaScript help you do something and can be used as many times as you want with the ability to use different arguments/values for each function call.
Parameters give functions superpowers. They allow you to pass arbitrary data to functions. Parameters are variables written inside the parenthesis in a function declaration. On the other hand, arguments are values that are passed to a function when it is called.
Parameters are variables used for passing arbitrary data to functions
Arguments are the values/data passed to such variables
The code below shows an add function with parameters a, b and calls to the function using different arguments/values for each call.
function add(a, b) {
return a + b
}
add(3, 4) // outputs 7
add(5, 6) // outputs 11
So What Then are Props?
Props are like regular function parameters in JavaScript. Parameters give functions the ability to not just be reused but to be reused with different arguments/values for each function call as you saw in the code above. As another example, let's take a component in React that simply displays the name of a car brand.
// Each car brand is displayed by the component
<DisplayCar brand="Aston Martin" />
<DisplayCar brand="Audi" />
<DisplayCar brand="BMW" />
The prop here is "brand". And the component has not just the power to be reused but to be reused with different values, more specifically, car brands. In other words, 3 different car brands are displayed using the same component rather than create 3 components for each car brand.
Understanding The Importance of Props
Rather than create 3 different components that display each car brand, the concept of props allow you to use the same component but with different values as you desire. So without props, you would have to create different components for each car brand you want to display which is way less efficient and not according to standard:
<DisplayAstonMartin />
<DisplayAudi />
<DisplayBMW />
The above is similar to doing this for the add function above.
function addThreeAndFour() {
return (3 + 4)
}
function addFiveAndSix() {
return (5 + 6)
}
Rather than doing this, a single add function could have been created with the ability to add two arbitrary numbers instead of creating several functions for each addition.
So remember, a function can be reused in JavaScript with different arguments/values because of its parameters. Likewise, a component can be reused in React with different values because of props. So you don't have to create new components that do the exact thing an existing component does already.
Another post would be out later in the future helping us understand a little more about props in React. In the meantime, kindly let me know in the comments section if this post helped you understand props to an extent.
Cheers!