React JS Tutorials

React.js is a JavaScript library that emerged from recent JavaScript paradigm shift: replacement of multi-page website with single-page application design. This site was made for traditional JavaScript programmers as well as complete novice to the craft. This React tutorial site was designed to help you save a trip to a book store and get started quickly.

Props

In React props is short for properties. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes.

The primary purpose of props in React is to provide following component functionality:

  • Pass custom data to your React component.
  • Trigger "state" changes (more on this later).
  • Use via this.props.reactProp inside component's render() method.

It's best to use camelCase formatting when creating your own React props just to stick to the commonly adopted standard.

I'll demonstrate this principle using a JSX example:


    <Element reactProp = "1" />

This "reactProp" (or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created using React library.


    props.reactProp;

Within React Component definition, these attributes then become properties attached to the React's native props object within component's constructor. But these props also become available inside the component's render method as well.

So how do we access props inside the actual React component? Let's take a look.

When starting out, these are the two common places you will use to access or "intercept" values stored in props object which was passed into your React component during creation.


    class Element extends React.Component {

        // Component's constructor
        constructor(props) {

            // Required to call original constructor
            super(props);

            // Props are now accessible from here
            var v = props.reactProp;
        }

        // This is called when ReactDOM.render is called on <Element />
        render() {

            // And from here
            return (<div>{this.props.reactProp}</div>)
        }

    }
    

This actually makes a lot of sense. We need to access props during initialization stage and also every time the component is rendered.

During the rest of this React props tutorial we'll learn what props are whether JSX is used or not. We'll also cover a few other practical examples just to see what props actually help us accomplish.

Using "props" without JSX

Note that it is possible to use React props without JSX. That means we have to use native React's function createElement. In it, props are passed as the second parameter in JSON format regardless of the number of props passed.

Here we also pass null, which in this case indicates "empty" innerHTML. Or more precisely, no children.


    React.createElement(Hello, { alertNumber : 1 }, null);
    

This is an exact equivalent of JSX version of this Hello element:


    <Hello alertNumber = "1" />
            

Yep, they are exactly the same. Babel's JSX transpiler converts these JSX (XML, actually) element tags into similar React.createElement object. And they can be used interchangeably.

You can use createElement safely here. However, using React props with JSX is the preferred method, but it requires babel plugin. If you are working outside of production environment and cannot use babel, you are going to have to live with non-JSX syntax, which is simply ES5 (EcmaScript 5) JavaScript functions with JSON. It is briefly covered later in this section.

You can use "props" in mixed components consisting of JSX and non-JSX elements

Because React allows mixing JSX-style elements with non-JSX elements, this tutorial will switch back and forth between the two formats, just to show you how props work in both cases. We will start with non-JSX based props that are used in "functional" components (They are the same as "stateless" components, as opposed to "stateful", but more about this in future tutorials, I want to keep this discussion on "props" isolated to itself to avoid any more confusion).

React "props" and states

React props are often used together with states. In this tutorial we will take a look at props alone in isolation. This way when we move on to states we can figure out which one is which, because while props and states are similar, they have a slightly different function and meaning in React.

Dynamic, often changing (updated) parts of your component are represented by props

React Components can be thought of as JavaScript functions that take "props" and return a React Element. React Components take parameters called "props" that may represent a dynamic part of rendered element, for example display a personal name in a "Welcome" message, or display the number of alerts for currently logged in user.

A React Component assumes three things:

  1. React props are the parameters of React Components
  2. Props are used to pass values that dynamically change contents of a React Component
  3. A React Component must have a return value of type React Element

Passing props to "Stateless" Functional Components

Props are often used together with states, but functional components do not support state. This does not prevent stateless and stateful components from being nested within one another without breaking React code. But we'll get to this a bit later, in fact, probably not even in this tutorial.

Props are React's way to store Component's "properties". What they actually are depends on the purpose of your component. Is it a timer? Then a prop of type Date (a JavaScript's built-in object for generating current date timestamp) can be passed. If your react component is a message welcoming a unique user, then a prop can be the username. If your component in an alert notification, the number of alerts can be represented by a prop.

Below we will take a look at an example of using React props to create a simple message in a "functional" component, a React Component created using a JavaScript function. We'll take a look at several examples:


  function Alert(props) { return <div>You have {props.alertNumber}</div>; }
  function Welcome(props) { return <div>Welcome to the site, {props.name}</div>; }
  function Clock(props) { return <div>Right now it is: {props.time}</div>; }

Note that the prop object will contain property names invented by you based on what your component should do, display or what values it should update when it's rendered.

These examples above may appear as JavaScript functions. But in fact they are all valid React Components, because they follows the 3 rules we mentioned earlier.

They all return a React Element and they all takes props as their parameters. Optionally, these props are used as part of the dynamic part of the rendered element, in this case used for various purpose: the number of alerts, username and current time.

React can use EcmaScript versions interchangeably. For example, in EcmaScript 6 you would create an equivalent React Component using keywords "class" and "extends", as shown in the following code:


    class Alert extends React.Component {

        constructor(props) {
            super(props);
            // Just to see what was passed...
            console.log(props);
        }

        render() {
            // You have 10 alert(s); notice trailing "s" uses ternary choice
            return (<div>You have {this.props.alertNumber}
            alert{this.props.alertNumber != 1 ? 's':''});
        }
    }

    var a = <Alert type = "1" alertNumber = "10" />;
    ReactDOM.render(a, document.getElementById('root'));

Note that by using curly brackets we can insert dynamically-rendered values into our React components. The following ternary operator is seen in the second set of brackets is shown in isolation below:


    this.props.alertNumber != 1? 's' : ''

Try switching alertNumber from "10" to "1". Once the component is rendered, the message will now read "You have 1 alert", without "s" in the word alert. That's what this ternary statement does. This is a common operation for displaying the correct word in plural or singular format, based on the numeric value passed into props just to stay in touch with proper English.

Also notice that as opposed to "functional" components we saw earlier (Alert, Welcome and Clock) in ES6-based classes, props are passed via their mandatory constructor function. The code above will render the Alert component, and output the following to the developer's console:


    Object {type: "1", alertNumber: "10"}

Whatever attributes you invent to pass to your custom Alert component, they will be attached to the props object, and become accessible within the render method itself. You just have to poke into it by using the "this" keyword as opposed to previous functional component examples, where we accessed props directly by props.name. In this case we sent the value 10 as alertNumber attribute.

The above example uses EcmaScript 6 and JSX. (The React Element is represented using

tags, typed directly into the JavaScript statement, that's what JSX does. Internally, it converts this code back to a valid React Element.)

Passing Entire Objects To React "props"

The props are passed to an ES6-style React Component at the moment of component creation as follows. You can have as many props as you want, and props can even represent objects, not just single values:


    class Alert extends React.Component {
        constructor(props) {
            super(props);
        }
        render() {
            return (<div>{this.props.info.username},
            you have {this.props.info.alertNumber}
            alert{ this.props.info.alertNumber != 1? 's' : '' }</div>);
        }
    }

    // Store conglomerate properties object in a variable first
    var properties = { username: 'Mark', alertNumber: 12 };

    // Pass entire properties object to Alert react component:
    var a = <Alert info = {properties} />;

    // Render "a" component
    ReactDOM.render(a, document.getElementById('root'));

In the example above we passesd an entire object to props, but first we singled it out into a separate variable. That's important! Note, that the following on the other hand will produce an error:


    // Error: we cannot pass entire objects as attributes
    // without first storing them in a separate variable
    var a = <Alert info = { username: 'Mark', alertNumber: 12 } />;

The above example will break React. That's because we must store objects containing multiple properties a separate variable, if we wish to pass an entire object as props to a React Component.

Here, Alert is a user-defined DOM element. In other words it isn't a <div> or <p> or any of the other common HTML tags. User-defined elements such as Alert are ones that are most likely to use props, because they define custom functionality.

Here "username" is used to store a string, and "alertNumber" is used to store a number, in the same way as you would use a standard HTML attribute like "class" or "id". Except in React Components you are allowed to use custom names that represent design of your element, a username or number of alert messages for example. The design is up to you.

It is possible to use ES6-style classes and not use JSX. Because at the core each React Component and Element are simply JavaScript functions, everything in React can be swapped around without destroying integrity of your code.

Notice, we have to rewrite the component's definition without JSX as well, in order to render it without JSX and then use ReactDOM's render method together with "createElement" method instead:


    class Hello extends React.Component {
        render() {
            return React.createElement('div',
                                        null,
                                       `Hello ${this.props.alertNumber}`);
        }
    }

    ReactDOM.render(

        React.createElement(Hello,
                          { alertNumber : 1 },
                            null),

                            document.getElementById('root'));

The above example writes out the React Element using React.createElement method, and passes props as its second parameter using JSON notation. Here, the third argument "null" is used to say that this element does not have innherHTML or any children. It's simply storing the alertNumber value in its props. The element is finally rendered into an HTML element whose id = "root".

In Conclusion

So what are props? Props are simply properties passed to React Components during their creation. It gets a bit more complicated when we get to React state tutorial, because we cannot operate on props directly (or should not) within the render method.

Later we will learn that mixing props and states isn't always a good idea, because React clumps states together to optimize DOM updates and by fiddling with props individually we might break that cycle and produce unexpected (overwritten) results.

We'll learn what all of this means in another tutorial, for now just think of props as custom variables you pass to your React Components, or "elements" if you want to call them here in that context.

Make a Donation

To support this site you can submit a donation to support these free tutorial articles that resemble book chapters. Tons of hard work goes into creating something like this, and your support helps run this website and continue serving useful educational material for JavaScript and React.js programmers.

© 2017 Copyright React JS Tutorials (reactjstutorial.net)

All content and graphics on this website are the property of reactjstutorial.net - please provide a back link when referencing on other sites.