React Basics For Beginners

React.js is a powerful, component-based Javascript library that allows efficient building of large applications with rapidly changing data.

There's a ton to learn with React, but here's some of the beginner basics to get you familiar with the framework.


Why Use React?

Virtual DOM

  • React is efficient because it employs the use of a Virtual DOM
  • Typical DOM manipulation is slow and inefficient as it requires rebuilding of the entire DOM for each update (for instance, if you have a list of 10 items, update one item in the list, the entire list re-renders rather than only that item).
  • A Virtual DOM, however, acts as a lightweight representation of the real DOM.
  • All updates are instead made to the Virtual DOM, which then compares to a snapshot of the Virtual DOM prior to the update, in a process called diffing. Through diffing, React can know exactly which DOM objects have changed, and then update only those objects on the real DOM, which in turn updates the user interface.
  • This greatly increases the speed of processing large data changes.

Other Functionality

  • Webpack functionality is taken care of by default with React. Webpack functionality is essentially used to minify and then bundle Javascript files together to allow the application to load more efficiently.

  • Babel functionality is also built in with React, which allows Javascript to be written in ES6, ES7, or ES8 syntaxes and converts it to ES5 which all modern browsers can understand.

Basics

Setting Up the Project

  • To create a React application, run npx create-react-app my-app-name

npx is not a typo. It is a package runner tool that comes with npm.

  • Run npm start to start the application.

  • Nearly the entirety of the code is written within the /src directory (with the exception of adding fonts and other CDNs such as Bootstrap to the <head> tag in index.html).

How Rendering Works

  • The entire virtual DOM is rendered in one native HTML element in/public/index.html:
<div id="root"></div>
  • This is done in index.js employing ReactDOM.render(), which is considered the entry point:
ReactDOM.render(
    // What to render
    <App />,

    // Where to render it
    document.getELementbyId("root")
);
  • <App /> refers to App.js. This is typically where you will import your components to build your app.

Writing in JSX Syntax

  • JSX (Javascript XML) is a syntax extension to Javascript which allows us to essentially write and visualize HTML in JS.

JSX is not specific to React, or required in React, but it makes things a lot easier. It is using React.createElement() behind the scenes.

  • Javascript expressions are written inside mustache braces ({}). With the exception of if/else, switch statements, and for loops that must be written in methods in class-based components, or using hooks (advanced concept).

  • "Class" is a reserved keyword in Javasjcript. All instances of the "class" property must be updated to className in JSX.

  • Any self-closing tags in HTML (such as <img> or <input>) need to be updated to a closing tag in JSX: <tag / >.

  • Comments in JSX can be written as {/* comment here */}.

  • Only one element can be returned by return() at a time. Can wrap in an empty <div> container or use a fragment <> that will not add bloat to the DOM.

Inline Styling in JSX

  • Style property must be an object rather than a string like in HTML
  • All property names are camelCase, and values are strings
  • Numbers default to "pixels" (eg. height, margin, padding, etc.)
  • Styles are passed in as a prop

Example:

const styles = {
  card: {
    margin: 20,
    background: "#e8eaf6"
  },
  heading: {
    background: "#9a74db",
    minHeight: 50,
    lineHeight: 3.5,
    fontSize: "1.2rem",
    color: "white",
    padding: "0 20px"
  }
};

function Navbar() {
  return (
    <div style={styles.card}>
      <div style={styles.heading}>Home</div>
    </div>
  );
}

Components

  • Components are essentially reusable functions.

  • Each component must import react:

import React from "react"
  • Each component must include export default componentName to be used in other components.

  • There are two ways to write functions in components:

  1. Functional Components - these are just plain Javascript functions and are stateless (unless you're using "hooks" which I don't cover here). They are easier to read and test than their Class counterparts and require less code.

Typically functions native to React are written with regular functions:

function componentName(){
    return ( JSX here );
}

Otherwise, functions should be written as arrow functions. Arrow functions are important due to the scope of this: In this case, this is not restricted to the scope of the function itself but rather belongs to the outside object.

const componentName = () => {
    return ( JSX here );
}
  1. Class Components - The below is identical to the above functional components. However, Classes allow the use of setState() (not covered in this article).
class componentName extends React.Component {
    render() {
        ( JSX Here )
    }
}

Props

  • Props are like inputs into components which are like functions, allowing you to pass data from component to component.
  • Props can be an arbitrary property name passed into the component:
<componentName propName=value />
  • The value can be accessed in the component via the props object:
    function componentName(props) {
    return(
     <div>
        <span>{props.propertyName}</span>
     </div>
    )
    }
    
  • Props pass data from component to component in unidirectional flow (parent > child)
  • Props can be passed through to more child components in a process called props drilling

There are many more advanced concepts for using React like State, Hooks, Context, and more. These are just the basics to get you started!

No Comments Yet