React Essentials: Props

React Essentials: Props

They're kind of a big deal

Props - explained

The React docs defines props as

When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.

They also use the following code snippet as an example

const element = <Welcome name="Sara" />;

Here we see that the "user-defined component" is Welcome and the object, or props, is called name with the value of Sara.

Let's see another example below ⬇️

Props - example

To start we have a functional component as shown below:

function MyComponent() {
  return (
    <div >
    </div>
  );
}

As we can see this component doesn't do anything, yet!

Let's add some magic 🪄 by passing the component properties, or props.

Passing Props

Below we create a variable called message and assign it a string of text.

Now the cool part 😎

Attach an object with any name (we use "secret" here) to the component as shown below

var message = "Props is now showing! Awesome!";
<MyComponent secret={message} />

Now notice here, unlike the example from the React docs above, message is surrounded by curly braces. This is because the value is JavaScript and must be enclosed in curly braces per JSX rules.

Similarly we could have just done

<MyComponent secret="Props is now showing! Awesome!" />

You've just successfully passed props! 🎉

Now we need to access it within the component, MyComponent.

Accessing Props

To access the props we need to pass an optional parameter to the functional component

This parameter can be any name you want - but it's HIGHLY advised to use the word props

function MyComponent(props) {
  return (
    <div >
    </div>
  );
}

Great - now how do we access it?

if we console.log(props) we get:

-> {secret: "Props is now showing! Awesome!"}

Just as we expected props is in the form of an object. To access it use the dot notation (props.secret)

function MyComponent(props) {
  return (
    <div >
      {props.secret}
    </div>
  );
}

Notice again that we didn't say props.secret - we used {props.secret}

Reminder in case you missed it earlier: this is because in React we use JSX and by using curly braces we are saying we want to display JavaScript code.

Important to note

Props is read-only. Meaning when we access props in the component we are not allowed to assign props a new value within the component.

If we want to assign props a new value it MUST be changed outside the component.

Recap

Now we have successfully passed props and accessed it in the component! 🥳

In the next article we will look at another fundamental topic: State