Skip to content

Instantly share code, notes, and snippets.

@leahgarrett
Last active June 24, 2019 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leahgarrett/02f600f408c4f97e944890f3dd954300 to your computer and use it in GitHub Desktop.
Save leahgarrett/02f600f408c4f97e944890f3dd954300 to your computer and use it in GitHub Desktop.
Introduction to React and Create React App

React

Topics we will cover:

  • Create React App, functional components, props
  • React Components and state, Life cycle and public API
  • Own API backend, Forms
  • React Router
  • Authentication
  • Testing React
  • Testing API
  • Deployment

Create React App

Why React?


What is React?

A library for building user interfaces. Just the UI of our web app. React is the R in MERN.

The MERN stack is equivalent to a Rails Application. We use Mongoose to generate our models, MongoDB for the persistance, Node and Express do the communication between the API and the models.

React got that name for a reason. It’s a component-based JavaScript library that renders smartly and can seriously simplify your work.

React has data and functionality grouped together in components. We have code to represent data and functionality, how we want to react to user interactions.

React hides complexity and provides extensibility. It is often used with other libraries and helpers.


Recognizing components

Look at example UI eg: twitter.

It would be really complicated to have all of this in one file. In React we break this down into components.


What is Create React App?

Create React App is comparable to rails new. It generates recommended basic dependencies and folder structure required to build a React app.

Create React App is created and maintained by facebook.

Dependencies include:

  • Babel - Allows us to write our code using ES6 syntax and JSX.
  • Webpack - There are alternatives but Webpack is most widely used and an accepted module bundler and task runner through out React.js community.

You don’t need to memorize all the plugins and what they do, just be aware that Create React App has selected a set of dependencies for us and that when googling you may sometimes find others are being used.

https://facebook.github.io/create-react-app/docs/getting-started


Folder Structure

We will be adding our js and css files in the src folder. You shouldn't need to edit files in the other folders.

my-app/  
  README.md  
  node_modules/  
  package.json  
  public/  
    index.html  
    favicon.ico  
  src/  
    App.css  
    App.js  
    App.test.js  
    index.css  
    index.js  
    logo.svg  

Code walk through

index.html
Contains a root element that React will be inserting HTML into. When using vanilla javascript we have been using a container element to insert our HTML.

index.js
Is where we write to our root element. Very similar to what we did in vanilla javascript.

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

app.js
This is the file for App Component. App Component is the main component in React which acts as a container for all other components.

app.css
This is the CSS file corresponding to App Component


What is JSX?

We can create elements in React using createElement

/src/App.js

function App() {
  const element = React.createElement(
    'div',
    {className: 'container'},
    'Hello World'
  )
  return element;
}

The React team made a way to create elements that feels more familiar to us; a way that is most like HTML. This conversion from JSX is made possible by Babel doing the conversion and Webpack running the updates.

/src/App.js

function App() {
  const element = <div className="container">
                    Hello World!
                  </div>
  return element
}

We can see what Babel does by using the Repl
https://babeljs.io/repl


A common way people use JSX is directly in the return statement.

/src/App.js

function App() {
  return (
    <div className="container">
      Hello World
    </div>
  )
}

Some differences between HTML and JSX

In HTML we use 'class' in JSX we use className.

Curly braces are different in JSX (more later).


Create an app to start experimenting

Install the Create React App package globally so we can use it in multiple projects
npm install -g create-react-app

Create the app
npx create-react-app first-app

Change into the app folder
cd first-app

Install dependencies
npm install

Run the app
yarn start

See a spinning logo?

Back at terminal lets open Visual Studio Code
code .


There must be a one parent element

Update the App component with the following code. This code will cause an error.

/src/App.js

function App() {
  return (
    <h1>Greetings</h1>
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
      </header>
    </div>
  );
}

The error displayed in the server log:
Line 8: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag.

Edit the code so there is one enclosing tag:

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Greetings!
        </p>
      </header>
    </div>
  );
}

Curly braces inside JSX

As soon as you use curly braces inside JSX you are exiting JSX land and entering javascript land. You can use any javascript that you want to as long as it evaluates to an expression.

String interpolation:
/src/App.js

function App() {
  const name = 'Universe'

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Greetings, {name}!
        </p>
      </header>
    </div>
  );
}

Using javascript to conditionally display one or another element using a ternary operator:
/src/App.js

function App() {
  const name = 'Universe'
  const selection = Math.random();

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Greetings, {selection > 0.5 ? name : 'World'}!
        </p>
      </header>
    </div>
  );
}

Using javascript to conditionally display an element:
/src/App.js

function App() {
  const name = 'Universe'
  const selection = Math.random();

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Greetings, {selection > 0.5 ? name : 'World'}!
        </p>
        {selection > 0.5 && <p>You are lucky!</p>}
      </header>
    </div>
  );
}

Challenge

  1. In the css file, after .App-logo add the following style:
.App-logo-small {
  height: 5vmin;
}

Use the ternary operator to change the class name of the logo to .App-logo-small when selection > 0.5.

  1. Refactor code to a local variable for selection > 0.5

  2. Add styles and use a condition to change the background color based on the time of day. Add at least three different colors, one for morning, afternoon and evening.

Hint: Use the javascript date method to work out the time of day
const hours = new Date().getHours();


Sample solutions below

.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
.App-logo-small {
height: 5vmin;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.morning {
background-color: yellow;
}
.afternoon {
background-color: dodgerblue;
}
.evening {
background-color: pink;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const name = 'Universe'
const selection = Math.random();
const check = selection > 0.5;
const imageClass = check ? "App-logo App-logo-small" : "App-logo";
const hours = new Date().getHours();
const backgroundColor = hours < 8 ? 'morning'
: ( hours < 16 ? 'afternoon' : 'evening');
return (
<div className="App">
<header className={"App-header " + backgroundColor}>
<img src={logo} className={imageClass} alt="logo" />
<p>
Greetings, {check ? name : 'World'}!
</p>
{check && <p>You are lucky!</p>}
</header>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment