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
  • Components and JSX
  • Learning Objectives
  • Components
  • Identifying Components
  • So -
  • Check it out!
  • Wait - What's that HTML doing in my Javascript?
  • Challenge: Greet the day!
  • todo We Do: Create a Dog component
  • todo You Do: Create a Human component
  • todo You Do: Add some styling to the Dog component ( create Dog.css )
  1. React (Updated 2019)
  2. Intro to React

Components and JSX

PreviousCreate React AppNextVirtual DOM

Last updated 3 years ago

Components and JSX

Learning Objectives

After this lesson, you will be able to:

  • Identify and define React components

  • Describe why we use components in React

  • Build a React component

  • Describe JSX

Components

The basic unit you'll be working with in ReactJS is a component. Components are pieces of our application that we can define once and reuse all over the place.

For an intro to components, watch (note: right click to open in a new tab!).

If you're used to writing out all of a page's view in a single HTML file, using components is a very different way of approaching web development.

With components, there is more integration and less separation of HTML, CSS, and JavaScript.

  • Instead of creating a few large files, you will organize your web app into small, reusable components that encompass their own content, presentation, and behavior.

When using React, building components will be your main front-end task.

  • Because they're so encapsulated, components make it easy to reuse your code, test, and separate concerns.

Identifying Components

  • Type in React Developer Tools in the search bar.

  • Install the extension ( may need to restart Google Chrome )

  • Look for a tab inside of the Chrome Dev Tools called Components

You should be able to see a component and it's properties

ach listing is a component. How can you identify this?

  • Listings look identical in structure, but have different information populating them

  • Listings are dynamically generated based on the user's search

Now take a look at the listing page. Scrolling down it, identify the visual "components" the website is comprised of. We suggest drawing this out on paper! So something like this...

As you're drawing this out, think about the following questions...

  • Where do you see "nested components;" that is, where are there components inside another component? Where do you see just one "layer" instead?

  • Are there any components that share the same structure?

  • For components that share the same structure, what is different about them?

So -

What does a simple component look like? Let's start with a simple "Hello World" example...

Code along: A Very Basic Component

In this section, we'll walk through:

  • Removing the pre-filled contents of your hello-world app.

    • create-react-app filled your app with sample content - let's make room for your app!

  • Adding your own component definition.

    • You want the app to display the words "Hello World!"

  • Going through what we've done in detail!

To start, remove the contents inside of the App component located in src/App.js file.

Next, let's create a file called src/Hello.js

Write the code below inside of Hello.js

// import React
import React from 'react';

function Hello() {
  return <h1>Hello World!</h1>
}

export default Hello;

Let's break down the things we see here...

import React from 'react'

We first start off by import React

function Hello() {}

This is the component we're creating. In this example, we are creating a functional component and calling it "Hello."

return()

Every component has, at minimum, returns some JSX ( HTML "like" syntax). The returns is what renders the component to the screen, so it controls what is displayed for this component. From this function, we return what we want to display.

  • In our case, we are rendering a "Hello World!" heading: <h1>Hello World!</h1>.

Note! That heading tag above looks like it's straight out of HTML, but it's actually a special language called JSX, which you'll see on the next page. For now, know that JSX will act like HTML when it's rendered to the screen.

export default Hello

This exposes the Hello class to other files. This means that other files can import from the Hello.js file in order to use the Hello component. In our case, we'll be importing it into App.js by calling an import to Hello.js.

When we try to import something from Hello.js, JavaScript will attempt to match a named export.

  • Our only named export in Hello.js is Hello.

The default keyword means that if we try to import anything from this file that the app can't find, JavaScript will automatically revert to importing Hello instead.

  • Only one default export is allowed per file.

Check it out!

Wait - What's that HTML doing in my Javascript?

This is currently the contents of our src/App.js file:

// import React, Hello component
import React from 'react';
import Hello from './Hello';

// define our Hello component

function App() {
  // what should the component render?
  // Whatever is returning from the Hello component.
  return (
      // make sure to return some UI
    <div>
        <Hello />
    </div>
  );
}

export default Hello;

Let's add a little styling inside index.css

html, body
  height: 100%;
  
body
  background: #333;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Helvetica Neue;
  
h1
  font-size: 2em;
  color: #eee;
  display: inline-block;

a
  color: white;
p
  margin-top: 1em;
  text-align: center;
  color: #eee;

Let's talk about the value that the render method returns. It looks an awful lot like an HTML heading, but it's not. We often write out React components in JSX.

So, JSX allows us to write code that strongly resembles HTML. It is eventually compiled to lightweight JavaScript objects.

Your Hello component returns:

  • Currently returns JSX, not HTML.

  • The JSX creates a heading with 'Hello World!'.

  • Your component reads this and renders a "Hello World!" heading.

React can be written without JSX. We won't be doing this. 👎🏽

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

var ui =
      React.createElement('div', {}, 
        React.createElement('h1', {}, "Hello World!")
      )

ReactDOM.render(ui, document.getElementById('root'))

Another example using React written without JSX.

var ui =
      React.createElement('div', {}, 
        React.createElement('h1', {}, "Contacts"),
        React.createElement('ul', {},
          React.createElement('li', {},
            React.createElement('h2', {}, "James Nelson"),
            React.createElement('a', {href: 'mailto:james@jamesknelson.com'}, 'james@jamesknelson.com')
          ),
          React.createElement('li', {},
            React.createElement('h2', {}, "Joe Citizen"),
            React.createElement('a', {href: 'mailto:joe@example.com'}, 'joe@example.com')
          )
        )
      )

    ReactDOM.render(ui, document.getElementById('react-app'))

Challenge: Greet the day!

  • Change your App component to display the Hello component multiple lines.

  • Add a line inside of your App.js below the last "Hello World!" heading that will display "It is time for tea." in an h3.

IMPORTANT: Remember, you can only return one DOM element. You can, however, place multiple elements within a parent div element. or a single fragment <>*

todo We Do: Create a Dog component

todo You Do: Create a Human component

todo You Do: Add some styling to the Dog component ( create Dog.css )

Take a look at (note: right click to open in a new tab!). We want to browse the page. Guess what, Tesla built their website using React. Let me prove it to you. Open a new tab. We are going to download the React Developer Tools from Google Extensions. Let's do that now. .

Go back to and inspect the page

Let us look at one more, (note: right click to open in a new tab!).

Components
Component diagram

Start your server ( npm start ). Now switch to your browser and navigate to , you can see your "Hello World!" heading. This app dynamically reloads each time you save, so you can check your changes at any point.

Tesla.com
Click here
Tesla.com
CraigsList
http://localhost:3000
this video