Post

React Cheatsheat

React Overview - 2024-05-11

Why React

atomic design

React allows you to build frontends in components and the components can be updated to form alternate components. This solves the problem of having way to many building blocks in your application.

React manages everything html, js, css in the same place

Thu 26 Aug 19:30:52 2021

Principles of React

  • React says “dont touch the dom ill do it, just tell me what you want the page to look like and ill take care of it”
  • React puts an app within a regular html div tag.
  • Build websites with reusable components.. just like lego blocks
  • React dev tools allows you to inspect your components
  • One way data flow - this is intentional and helps with debugging
  • React is not a framework it is just a frontend ui, React only cares about components and virtual DOM (its just the view).

npx create-react-app was created to easily get a dev environment setup without having to configure webpack and babel etc

Wed 25 Aug 19:30:13 2021

  • React creates a virtual dom which it updates dyamically when stuff is changed - Virtual DOM reduces the number of re-renders of the actual DOM.
  • React works with flux (one way data flow from top to bottom, updates move from parents to children)
  • See github for all the commits for this tutorial
  • React is frequently used with other technologies to create fullstack applications
  • React uses the virtual dom this allows you to update content on the page without reloading the page

Components

  • Components return the rendered html.
  • Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

React components are what makes up a react built UI. Props are commonly parsed to components to make them more dynamic.

  • Components are capitalized
  • Components are based of es6 classes
  • each component is just a function that rerenders when state changes

  • When a react component is told to re-render the component will also re-render any child components.

  • Decide on components
  • Try to think in components with react - everything needs to be a component
  • You can create a component in 2 ways, with functions or a class
1
2
3
4
5
import Button from './Button';

<Header/>
<Button/>
<Tasks/>

COMPONENT TYPES

  1. Stateless functional components: contain js functions that return html
  2. Stateful class components: must contain a class extending a component task. Must contain a render method returning html.

Nest components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Profile() {
  return <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />;
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

Import components

import the Movie component from the components folder

1
import Movie from "./components/Movie.js"

more info

React State

We use state for variables whose value can change over time, and that when changed should trigger the component to re-render with the new data. Essentially, we use state to make our components interactive

  • Changes to the state can only trickle down to child elements they cant move up to parent elements
  • What changes when state change
  • The states can become difficult to manage use the context api which is built into react to help manage state Key to success: decide the state and where it lives
  • State can be an object of properties

setState

  • setState is an asynchronous function call
  • setState has a callback function which solves state not updating correctly due to its asynchronous nature
1
2
3
4
5
6
7
8
9
10
// Wrong
this.state.comment = "Hello";

//Instead, use setState():

// Correct
this.setState({ comment: "Hello" });

//setState with callback function to run after setState
this.setState({ searchField: e.target.value }, () => console.log(this.state));

React State and Components

  • State is declared in one place and trickled down as props for use in child components
  • Components can have state - like a menu can have an open / close state
  • You can pass in props which helps to add dynamic values into the content
  • Sometimes you want to share that state across multiple components - app or global state
  • Function components allow you to use state through hooks - such as the useState hook
  • When you call setState in a component the component will rerender

React Props

  • Allow components to use dynamic values
  • A variable that a component can pass from a parent component (app.js) - the value is set in the component
  • Into a child component (employee.js)
  • Props are parameters passed to a component or function
  • Props can be functions booleans, strings or numbers
  • Use props when you want to pass values to a function or a component
  • Props is a javascript object (key value pair)
  • In App.js render the employee component using the prop name=”value”
1
2
3
4
5
6
<div className="App">
  <Employee name="Jack" />;
  <Employee name="Brian" />;
  <Employee name="George" />;
  <Employee name="harry" />;
</div>
  • In Employee.js output the html using the dynamic prop value
1
2
3
4
5
const Employee = (props) => {
  return <h1>this is an {props.name}</h1>;
};

onAdd = { addTask };

Destructuring Props

  • pluck out name from the props object and create a variable for it
  • now you can use {name} rather then {props.name}
1
const { name } = props;

Props vs State

React components can have 2 forms of data: props and state.

Props are properties received from ancestors in the component hierarchy, and cannot be changed, or mutated.

State is local to a component, and can be changed by events. Child components can receive both the values of that state and events to update that state through props.

React Hooks

You can tell a hook because it starts with the word use.

useState

Use the useState hook to update the rendered values of a react component.

  • Use hooks inside function components
  • Hooks must be called in order - meaning you cannot put hooks inside of if statements, loops or functions
  • When you update the state your component re-renders

setState

  • to update the state use setState
  • setState can also take a function which takes in the previous state value
  • the default value is the constructor
  • if the constructor value is a function its only ever run once
  • if the constructor value is a static value like 4 its run everytime
1
2
3
4
import { useState } from "react";
const [name, functionToUpdateName] = useState("default state / constructor");

functionToUpdateTheState("new content to update the state variable");
  • updating state is oneWay data - you only send new data to the state
  • you can set component level state or app level state
  • check the state of a component (what value the component has) in the react dev tools inspector
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//another example
const [currentState, setNewState] = useState("default Value");
//output the state

{
  currentState; // {currentState} will output 'default value'
}

//basic set the new state use
setNewState("new state value");

//setNewState with function and previous value

setNewState((prevValue) => "some more text");

//setNewState with function and previous value

setNewState((prevValue) => "some more text");

useEffect

Useful for running code that needs to run on every render. The useEffect() hook is a wrapper that helps prevent side effects, such as when your state needs to re-render the component.

Getting started

  • notice in index.js that app is imported
  • you can write javascript directly in the jsx
  • you can create your own components. its best to use snippets for this
  • if you use a class based component then you need to import react from react at the top of the file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export const Header = () => {
  return (
    <div>
      <h1> My Header </h1>
    </div>
  );
};

//class which uses the render method
export default class Header extends React.Component {
  render() {
    return (
      <div>
        <h1> My Header </h1>
      </div>
    );
  }
}

Notes: probs jan 2020

Creating a new functional component:

try to use functional components instead of class components as much as possible

  • always import React from ‘react’
  • always export your component to the default app.
  • always import your component in app.js
  • then include it in the app component as html element
  • you can write your functional components using arrow functions
  • funcional components do not use the ‘this’ keyword
  • funcional components are mainly responsible for the ui
  • funcional components are also called stateless components (not true now that we have react hooks), dumb components or presentational components.

When creating a class component

  • you must import react and the component class from react
  • must extend the class from the react component
  • must include a render method returning null or html
  • must export the class
  • import it in app.js
  • include in in the app component
  • class components are feature rich.
  • can maintain there own private data (state)
  • complex ui logic
  • otherwise known as stateful components, smart components, container components

  • hooks are a new feature that lets you use state and other react features without writting a class.

What is jsx?

javascript xml - js extention. for writing xml like code for elements and components. you can use react without jsx but jsx makes your react code simpler and elegant jsx makes use of camelcasing propery names: class is now className, onclick is now onClick, tabindex is now tabIndex

props is short for properties allow the component to be dynamic to specify props for a component we specify them as attributes

jsx

1
const title = <h1>Hello, JSX!</h1>;

Send values to your component

1
</Mycomponent name = "bruce">

Retrieve values from your component in the component file

1
2
3
const Mycomponent = (props) => {
  return <h1>hello {props.name}</h1>;
};
  • the curly braces is a feature of jsx which is used a lot in react applications
  • the return element can return only one html element.
  • thats what the main div tag is used for.
  • anything returned outside of the div will cause an error
  • props.children will render any child elements being passed.
  • on the class component you can use the this keyword to access properties.
1
return <h1>hello {this.props.name}</h1>;

Props are immutable meaning their value cannot be changed

props vs state

  • props get passed to the component where as state is managed within the component.
  • props are immutable as they are passed down by the parent.
  • state can be changed because its managed within the component.
  • a state is an object that is privately maintained in a component.

destructuring

  • destructuring is the act of extracting the nessesary props for better syntax.
  • destructuring usually takes place in the render method.
  • you can use destructuring in functional components and in class components. example:
1
const { name, heroname } = this.props;

React Components

React puts interactivity first

Traditional html pages put html first and sprinkle in js as a secondary interactivity

React flips this concept - a React component is a JavaScript function that you can sprinkle with markup

Export

1
2
3
export default function Profile() {
  return <img src="https://i.imgur.com/MK3eW3Am.jpg" alt="Katherine Johnson" />;
}

Return statements

Return statements can be written all on one line, as in this component:

1
return <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />;

If your markup isn’t all on the same line as the return keyword, you must wrap it in a pair of parentheses:

1
2
3
4
5
return (
  <div>
    <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
  </div>
);
This post is licensed under CC BY 4.0 by the author.