How would you React to some React Reactions.

React Workshop & Information

JJ Bastida

General Info

Before we start the lesson...

React should really only be done if you have a good knowledge of HTML, CSS, and Javascript. It should not be attempted if you do not understand standard web code.

Be sure to download and install Visual Studio Code & NodeJS.

When everything has been installed run the following commands on your Terminal, Powershell, or GitBash in a new folder somewhere on your computer in a safe location:


npm i react This will install the React library on your machine for this project.

npx create-react-app react-app This creates a base React app folder. Be sure to replace "react-app" with whatever you app is named.

After the app folder has been made it cannot be previewed or worked with in the same way regular HTML files can. A React project needs to be parsed and rendered before it can be seen.

With web apps, when using library packages you need to install them to the project, using NPMjs is a great resource for easy to implement packages.

To properly view and render out your React app you will have to run one of the commands below. It auto-refreshes so be sure not to run the command more than once.


npm run start This will start the app and render it out locally in browser (not for export, only for preview).

npm run build This will build the app and render it out as html, it creates a build folder (put the contents of the build folder in a public_HTML folder to have it online).

Try to keep components organized using folders and appropriate names.

Make components as re-usable as possible, and if a single component is becoming too big, try breaking it up into multiple smaller components.

What do I React to?

Is this like JQuery? Like a library??

React is a Javascript framework made by Facebook that allows you to make web apps with ease. A web app is a web project that renders out as HTML but is generally written and constructed in a different language or framework. This allows for more complex code, more structured layouts, and/or re-usable components.

React works in a way that, to many, looks like a combination of HTML and Javascript. It allows for quick and easy HTML re-renders with minimal effort and dynamic content.

React files are type .jsx and must be named with PascalCase to actually work within React.

At it's core, React works by creating code blocks called components and by passing props. A component can be used endlessly within other components and allows for easier and more structured code. And props are simply variable values that can be passed between components with ease.

The other main selling point is being able to have javascript directly in your HTML, and have things change on the fly.

When starting work on a project, you should work off of the App.jsx. It's best practice to have static components (like a nav or footer) in the App while the page contents change per route. See routing for more

React will generally look something like the following:


class TextingMeAtFourAM extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (<>
            <h1>
                This is a big title; Why you comin home 5 in the morning...
            </h1>
            <p>
                {this.props.description}
            </p>
        </>);
    }
}
                

Components AND Props?

It can be the messiest thing or the cleanest thing on the planet.

A component is simply a section of code that can be re-used endlessly throughout your web app.

Components will render out whatever is being returned from the render function, or in the case of functional components, whatever is returned.
In the following case, the PropBaby is being rendered in the PropDaddy. The PropBaby is just a p tag. So when it becomes HTML it'll just be one p tag.

Props are one of the fundamental ways of how React allows information to flow. It's always better to use props or import data rather than hard code values, this allows components to be much more reusable.

Props can be any variable type, including numbers, boolean, arrays, objects, or even functions. To pass something that isn't a string, be sure to wrap it in {squigglyBrackets}.

Be careful with the types of props that are passed. If you pass a function and try to make it work like a string the render might fail.

Also keep in mind, props that are passed are read-only. You cannot change a prop in a child component.

Components can be written as class based or functional components. See below for more on Functional Components See my JS workshop for a refresher on classes.


class PropDaddy extends React.Component {
    render() {
        return <PropBaby name='Baby'/>;
    }
}

class PropBaby extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return <p>{this.props.name}</p>;
    }
}
                

States, life cycle methods, refs, and more!

Everything happens at some point, but when is the real question.

When working with React it is important to remember that it does not work in the same way a regular HTML site does. The code is rendered out but continues to stay alive and open to re-renders depending on a lot of different things.

This also means that a lot of values are changed asynchronously so that other processes can run at the same time without slowing down the web app.

Here are just a few of the tools people use in React to achieve dynamic content.

State - A state is a user-defined javascript variable that can be changed on the fly. States are set different to that of a variable, and are available globally whenever needed (per component or can be passed as props). You cannot modify states by doing this.state or changing values directly. They should be changed with the proper setState() accompanying function.

Refs - A ref or reference, is a reference to a mutable value that can be modified on the fly. Different to a state, it can directly reference an HTML element and is in an object structure (not just a value).

ComponentDidMount - Is an effect method that fires as soon as the component renders. It fires after the render function successfully mounted.

ComponentWillUnMount - Is an effect method that fires as soon as the component un-mounts and is no longer available on the page. This is usually used for cleanup of unused event listeners or state management.

Context - Is a global state manager that allows you to use global states across different components with ease. It can be a little annoying to set up though.

Routing

It's okay to slug around. I won't judge.

Routing can be done in a multitude of different ways with a multitude of different libraries.

The one that gives the most granular control would be React Router DOM

With the React Router DOM you can easily set url routes, pass props to pages based on url, and create easy 404 pages.

Router - The Router is the main container that controls all of the routes and does a whole bunch of magic.

Switch - The Switch is the specific component that allows the router to switch between routes depending on the route.

Route - The Route is the single URL route, it can render a single component or even a group of components with props.

There are many different properties that you can pass into these components, have fun and look into their documentation for more.

This is an example Router; it should be placed in your App render instead of whatever content you have for the page.


return (
    <Router>
        <Switch>
            <Route
                path='/about-me'
                component={AboutMe}
                exact
            />
            <Route
                component={NotFound}
                status={404}
            />
        </Switch>
    </Router>
);
                

Synthetic events

Don't worry they're allllll real.

React makes component events incredibly easy and allows for a lot of different modifications on the fly!

Events are made using a slew of different event props which take a function to run when the event is done.
If you pass anything that isn't a pure function it will explode.

If you want to call a function with props be sure to wrap it in an anonymous function.
() => {doSomething('Hello');}


return (
    <div>
        <button onClick={Eggplant}>
            Touch me for Eggplant!
        </button>
        <Crab 
            onMouseDown={() => SpinCrab(40)}
            onKeyDown={DontSpin}
            >
    </div>
);
                

Functional Components

Functions; hook, lines and sinker!

If you're still here, congrats, this is where React starts to get super fun and easy to understand!

React is 6 years old at this point, and in mid 2019 they perfected and cleaned up functional components in a way that makes React so much more beautiful and easy to read.

Functional components, as the name states, are components made with functions instead of classes!

They make clean code management a lot easier, and hooks (explained later) make React beautiful again.

The React code on the right is a simple functional component. It doesn't need a constructor, or this.props. Everything works as it normally would and even the React imports stay the same.


function AnimeWaifu (props) {
    return (
        <div>
            <img href={`/images/${props.imgURL}`}>
            <h1>
                {props.name}
            </h1>
            <p>
                {props.description}
            </p>
        </div>
    );
}
                    

Hooks!

What did you just call me!?

A hook is essentially a simple reusable function that accomplishes a local task per component.

React has a few default hooks (explained below) but you can always make your own as well!

Before diving into using hooks, remember you should only ever use hooks inside of the functional components at the top level (in the component function), not inside of loops or if statements, and definitely not inside of other functions within the component.

useState - Allows you to create easy to use states and an accompanying setState function with ease!

useEffect - Allows for effect functions that listen for a certain variable to change, and fire when certain variables change.

useRef - Allows you to make a ref but a lot more streamlined.

useContext - Gives you access to states and values exported from contexts with no complex imports or wrapping.


function HeirToTheHair () {
    const [hairColor, setHairColor] = useState('Please write a hair color...');
    const hairInput = useRef();
    const userProps = useContext(UserContext);

    useEffect(()=>{
        if (hairColor !== userProps.globalHair) {
            userProps.setGlobalHair(hairColor);
        }
    },[hairColor]);

    return (<>
        <input ref={hairInput}>
        <button
            onClick={() =>
                 setHairColor(hairInput.value)
            }
        >
    </>);
}
                    

Help & Troubleshooting

NOTHING IS RENDERING!?

Check that everything is spelled correctly & that everything is importing properly.

Check again!Trust me check your code again to be sure you didn't miss anything.

Use the Developer Tools Inspector generally by right-clicking and selecting inspect.

Console.log your props or variables to make sure you have the right data.

Be sure that your CSS is applying properly, and make sure that your components are ordered in the right way.

Try searching online for the error you are receiving.

If a build is failing, try doing run start and seeing any errors or warnings that appear in the console.

Try Google-ing the problem.

Common React Errors

My <FatBaby> component isn't getting props from <Mama>

Be sure to check the following:

Check that everything is spelled correctly & that your components are properly imported!

Make sure that all components are properly wrapped in one big container or React Fragment!
A react fragment looks like this <> </> or <React.Fragment> </React.Fragment>

Make sure synthetic events are receiving functions (not a function call)

Make sure the props being received are the right type you are expecting.

Make sure you know how things are timed, you can't use a ref unless it's in an effect (because it will probably be null).

Make sure your components are properly returning the right tags (and follow them down the tree if needed).

Check your routes.

Check library documentation.

Make sure all of your tags are properly closed.

Make sure React is either returning components, a function, or null. It doesn't like strings, numbers, booleans, or undefined.

Advanced Tips!

For all you cool kids 😎

De-structure your props to make them easier to use and understand! De-structuring allows you to use your props without having to reference the object every time.
const {name, image, description} = props; or function Baby ({name, image, description}) {...}

Using short-circuit operators and quick conditional statements help make React feel much more dynamic and make code a lot shorter!

&& The && operator will run the last function or variable in the order they are placed.

|| The || operator will run the whichever of the variables returns true first.

__ ? TRUE : FALSE This quick conditional statement checks whether the first value is true or false and runs the corresponding code.


const loggedIn = props.loggedIn || false;
const getDate = () => new Date().format();

return (<>
{loggedIn ? (
    <p>
        You're logged in!
    </p>
): null}
<p>
    {!props.date && getDate()}
</p>
</>);
                

A simple and quick way to display data is to use what is called a map. You can take any array and use the map method to return a modified array of items.

In React, a map can return multiple components in succession meaning that you can take a lot of data and render out the same item with different data very easily.

Don't forget to add a unique key value when mapping to the outer most container! React needs keys to help it manage maps and maintain them well.


const dataSample = [{
        title: 'Snails!?',
        body:'What is it?',
    },
    {
        title: 'Clams!?',
        body:'What on earth??',
}];

return (<>
{dataSample.map(({title, body}) => (
    <Card key={title}>
        <h3>{title}</h3>
        <p>{body}</p>
    </Card>
))}
</>);
                

That’s all for now!

Be sure to contact me if you have any questions or concerns