What are props?


#1

Question

What are props?

Answer

To properly understand one of the most essential features of React, which is the ability to pass data between components, we need to know the meaning of props and what they are. We have a lesson here that helps us understand part of it.

Props stand for properties which are arbitrary inputs to a component, where a component is pretty much like a JavaScript function in that sense, so no matter if we have this:

class MyComponent extends React.Component {
  constructor(props){
    super(props)
  }
  ...
}

export default MyComponent;

where we make sure to register the props (input) received by the component using the constructor method and calling super which reaches to all the methods that recognize props from the class React.Component. Or we can have this, thinking that props has a name property:

function MyComponent(props){
  return <p> This component has a name, and it is: { props.name }</p>;
}

As the lesson mentions props is an object, for example in our siblings lesson our component is being passed an attribute name that contains the state of the parent component, that name becomes a property in our props object allowing us to have a reference of a value that we will receive when our component is rendered, looking back at the function MyComponent, lets say we exported it and now we want to call it in another function from another file, that might look like this:

import { MyComponent } from './MyComponent'; //as in ES6+

function ParentComponent(){
   const name = 'Axel';
   return(
     <div> MyComponent({name}); </div>
   )
}

There we have called our component in the parent function and passed an argument object with a property name. This in React will look like so:

import React from 'react';
import  MyComponent  from './MyComponent'; //quite the same with the exception of the component export dictates how you get to import.

class ParentComponent extends React.Component{
  constructor(){
    this.state = {
      name: 'Axel'
    }
  
  render(){
    return(
       <div> 
        <MyComponent name={ this.state.name } />
       </div>
    )
}

So now we have revisited that props is an object created by React to manipulate more efficiently how data is passed to components; just like functions receive arguments (value passed to a function when is being called) and handles them through parameters (stand in value set between the function parenthesis when declared to state that there must be a value passed when the function is called) to fulfill their task. If we ever forget where props are coming from, we can always trace them by checking where has our component been imported and where it has been called.