SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Learning Objectives
  • Component Data with Props
  • todo You Do hello-world Exercise
  • What about... multiple props?
  • What about... multiple props passed from an object?
  1. React (Updated 2019)
  2. Intro to React

Props

PreviousVirtual DOMNextDino Blog Activity

Last updated 3 years ago

Learning Objectives

After this lesson, you will be able to:

  • Describe props

  • Create a component that renders props

Component Data with Props

The React framework was built to handle data that changes over time.

So far, we have defined a Hello component inside App.js. The component's returns a div with a <h1> heading, written in JSX.

In index.js, we are importing the Appcomponent and all of the contents inside ( i.e. <Hello />). We are appending the App component to the virtual DOM, and rendering that in the root node. Cool!

This is great, but it doesn't involve any data yet, let alone data that changes over time! Let's make it more interesting.

Rather than simply display "Hello world", let's display a greeting to the user. We'll make the greeting change dynamically based on the user's name.

The question is, how do we add a name to our Hello component without hardcoding it into the component's return statement?

Find out! Try it yourself alongside in (note: right click both for new tab!)

todo You Do hello-world Exercise

Code along: Adding props to our component

Let's use props to make our "Hello World" app more flexible.

First, a single PROP

We want to make a greeting that's reusable for many different users, so we'll have a name prop for the name of the user.

In your src/App.js, we'll change the line that renders the Hello component to include this name prop. The new line will be:

<Hello name={"Jay"} />

We pass in data wherever we are rendering our component. In rendering the Hello component above, we pass in a prop called "name" with a value of "Jay".

Your App.js should now look like this:

import React from 'react';
import Hello from './Hello.js';

function App() {
  return (
    <div >
      <Hello name={"Jay"} />
    </div>
  );
}

export default App;

Now, every time we render our component, we will pass in data.

  • When the Hello component renders, we pass the Hello component a prop called name with a value of Jay.

If you check your application now, look at the React Developer Tools nothing has changed. We're passing the name prop into the component, but the component isn't using it yet.

In our Hello component definition, we will add props as a argument to our Hello function (props){}. Next, change the <h1>Hello World!</h1> to <h1>Hello {props.name}!</h1>. The portion {props.name} deserves a closer look:

  • props is an OBJECT that will collect all the props that were passed down to it from the parent component App

  • props.name pulls out the name property from props and returns value Jay.

The {} syntax in JSX renders the result of any expression inside it. It works even without props. If you wrote {2+2} in your JSX, 4 would be rendered.

In App.js, your Hello class should now look like this:

function Hello(props) {
  return (
    <div>
        <h1>Hello {props.name}!</h1>
        <h3>It is time for tea.</h3>
    </div>
  );
}

In the above example, we replaced "world" with {props.name} = Jay.

What about... multiple props?

Of course, we often want components to display more complex information. To do so, we can pass multiple properties to our component! We'll use the same two steps we took to add the first prop.

First, add another prop to the component call: <Hello name={"Jay"} />, changes to <Hello name={"Jay"} age={24} />.

Update your App.js file to reflect this:

import React from 'react';
import Hello from './Hello.js';

function App() {
  return (
    <div >
      <Hello name={"Jay"} age={24} />
    </div>
  );
}

export default App;

Now, in our component definition we have access to both values. The second step is to change the Hello component class in App.js to use the age information!

function Hello(props) {
  return (
    <div>
        <h1>Hello {props.name}!</h1>
        <p>You are {props.age} years old.</p>
        <h3>It is time for tea.</h3>
    </div>
  );
}

What about... multiple props passed from an object?

If we have many props, it might get difficult to keep track when we're passing everything. A better practice is to organize values in some kind of object and then pass props to the component from that object. Let's see this strategy.

Currently, in App.js, we put Jay's name and age directly into the Hello component. Instead, we'll create an object that holds Jay's name and age, making it clearer for other developers and easier to change in the future. In your App.js file, below the import statements, add this object definition:

let person = {
  name: "Jay",
  age: 24
}

Next, we'll update what's passed into the Hello component:

function App() {
  let person = {
    name: "Jay",
    age: 24
  }

  return (
    <div >
      <Hello name={person.name} age={person.age} 
      />
    </div>
  );
}

export default App;

We don't have to change anything in Hello.js, because it's still receiving exactly the same values for exactly the same two props - name and age. We're just sending it those values in a slightly different way.

Try changing the values inside the person object. See how the page updates.

Multiple props from a more complex object

Since we're just pulling props out of an object, we can use any object we want. For example, we can nest an array inside it.

Let's say our user has some favorite animals. Update your object to include an array:

let person = {
  name: "Jay",
  age: 24,
  favorites: ["Dogs", "Tigers", "Lions"]
}

Now we can use this new information as a prop, just like normal. You could choose to pass a single element (favorites[0]) or the entire array. We'll use the entire array so that the component can display all a person's favorite animals. First, update your ReactDOM.render() call in index.js:

function App() {
  let person = {
    name: "Jay",
    age: 24,
    favorites: ["Dogs", "Tigers", "Lions"]
  }
  
  return (
    <div >
      <Hello
        name={person.personName}
        age={person.personAge}
        animals={person.favorites}
      />
    </div>
  );
}

If you check your application now, nothing has changed. Remember, a component class will just ignore any props it receives that it doesn't use. But, we want to use the favorites! Therfore, next, update your Hello component return statement

<div>
  <h1>Hello {this.props.name}!</h1>
  <p>You are {this.props.age} years old.</p>
  <p>You love: {this.props.animals}</p>
</div>

If you check the page now, you'll see React prints the entire array, as that's what was passed in. If we wanted to include all the animals clearly, we could fix the spacing. Instead, to review some syntax, let's just modify the code to render the last animal.

<div>
  <h1>Hello {this.props.name}!</h1>
  <p>You are {this.props.age} years old.</p>
  <p>You love: {this.props.animals[2]}</p>
</div>

If you want to learn more.

Check it out! You should be able to browse to to view this change!

Check it out! You should be able to browse to to view this change!

Check it out! If you browse to nothing should have changed.

This link is also in the Further Reading page at the end of the React module, under the Facebook documentation.

this video
this codepen
http://localhost:3000
http://localhost:3000
http://localhost:3000
Read more about using props in JSX, if you'd like!