Handling Data with Props in React

Trey Alexander Davis
Byte-sized React
Published in
2 min readSep 7, 2017

Props to you my friend for making it this far.

So far our components have been static- let’s change that by passing down some data to our components.

Passing and accessing data in react components is fairly straight forward. Using JSX we pass data to a component as an attribute:

<MyComponent someAttribute={data.value} />

In JSX the curly braces indicate a JavaScript expression which must return a value. The passed data is accessed via props in the defined component:

const MyComponent = props => {
<p>{props.someAttribute}</p>
};

Now let’s walk through an example in CodePen (if you don’t have a free CodePen account or don’t know how to set up CodePen for React, check out this story)- first lets define some dummy data in our JS file:

const blogData = {
title: 'My blog title',
body: 'Arcu viverra dolor eros interdum,
quis nonummy accusantium at lorem luctus iaculis.'
};

Next let’s define our blog components:

const Heading = () => {
return (
<h1>My Blog</h1>
);
};
const Blog = props => {
return (
<div>
<h2>{props.title}</h2>
<p>{props.body}</p>
</div>
);
};

Noticed how we used the props object to render the title and body values that will be passed to the Blog component. Props is read-only or immutable, so we don’t have to worry about changing the props values.

Before we write our App component, we need to protect our component be defining the variable type that will passed down to each prop. We will define this using React.PropTypes. Add the following to your JS file:

Blog.propTypes = {
title: React.PropTypes.string,
body: React.PropTypes.string
};

Here we are defining that the the data passed down to our Blog component will be strings for both title and body. Check out React’s documentation for a list of all propTypes.

Now let’s put this together in an app component and pass down our data:

const App = props => {
return (
<div>
<Heading />
<Blog title={blogData.title} body={blogData.body} />
<Blog title={blogData.title} body={blogData.body} />
<Blog title={blogData.title} body={blogData.body} />
</div>
);
};

Finally, let’s render our app (be sure to add a root div tag to the HTML file ):

ReactDOM.render(
<App />,
document.getElementById('root')
);

Your CodePen should look like this:

Let’s break down what’s going on here- red indicates code explanations, blue indicates data flow.

Here is the CodePen:

Great- now you are passing data to components like a pro. Next we’ll take a look at rendering arrays in React so we don’t have to list our Blog component 3 times :)

--

--