< Previous: Importing React Components using ES6   Next: Generating Random Values for Our Page >

What are React Props?

When you use any React component you can pass it some input data that you want it to work with. These properties are called "props" and are read-only values that define the basic starting point for a component.

In JSX, props look just like HTML attributes. To demonstrate this we're going to modify our application so that the Detail component can have its message changed from elsewhere.

Change index.js to be this:


import React from 'react';
import ReactDOM from 'react-dom';

import Detail from './pages/Detail';

    <Detail message="This is coming from props!" />,

Note the new message="This is coming from props!" attribute to the Detail component. In Detail.js we need to make it read from the message prop rather than a hard-coded string, but that's easy enough to do:


import React from 'react';

class Detail extends React.Component {
    render() {
        return <p>{this.props.message}</p>;

export default Detail;

Notice how I've written this.props.message inside braces? That's because it's JavaScript code rather than plain text. When your app gets built that part gets executed as code so that the input message is used rather than a hard-coded string. If you go back to your web browser you'll see it should have updated with the new message. And if you go into index.js and change the message there, it will update again – great!

Before we continue, it's important I clarify that props aren't strictly read-only, and indeed you can change them at any point if you wish. However, doing so is very strongly discouraged: you should consider them read only for the component they belong to, and change them only from the component that created them. That is, if you created a component and gave it some props you can change those props later if you want to, but props you receive (i.e., this.props) should not be changed.

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: Importing React Components using ES6   Next: Generating Random Values for Our Page >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.