React overview

React overview

summarizing this interface-building JavaScript library

·

2 min read

Intro to React

React:

  • is a JavaScript library that builds user interfaces

  • began in the early-2010s by Meta (aka Facebook)

  • focuses on components (and therefore code re-usability)

  • manages real-time changes in data (known as state)

When we use React, we usually use it to:

  • gather JSON data (via fetch or async/await) into variables, which we can then:

    • pass into various React components

    • visualize using JSX (a syntax similar in appearance to HTML)

  • listen to user input (clicks, changes, keystrokes, mouseovers, etc.)

    • with handler methods
  • manage changes in state (i.e. changes in the data)

JSON as the desired data format

  • JSON ("JavaScript object notation")

    • we want data in this format so as to build the UI

    • differs from actual JavaScript objects in that it has a more strict notation

JSX to make interfaces

  • JSX ("JavaScript XML")

    • the markup language we use to consume the data by building out the web app's structure

    • has a very HTML-like syntax

    • unlike HTML, it allows for variable or conditional "what-if" types of renderings

A sample of JSX lies inside the return statement (which renders the UI) in the following example:

function App() {
    const appName = "joncoded"
    return (        
        <div className="App">
            <p>Welcome to ${appName}</p>
        </div>
    )
}

Component as a file

As we can see from the previous code snippet, most of the DOM manipulation work happens before the return (render) statement! There we can do "programming things" like:

  • declaring state variables

  • proposing handler methods for events

  • fetching data from external sources

  • assigning (miscellaneous) variables

Thus, a React file (simply just a .js file) consists of:

  • a function with

    • some programmatic instructions using JavaScript

    • a virtual DOM render using JSX

Re-using components in other files

We could then "call" that function in another React file by importing it and using JSX:

import App from './App'

function AnotherApp() {
    return (
        <>
            <h1> Wrapper App </h1>
            <App />
        </>
    )
}

Note the use of the HTML-like syntax for <App /> and how JSX differs from HTML:

  • The self-closing tag happens more frequently in JSX

    • <App /> as a short form of <App></App> (which can also happen)
  • The tags can have a variety of names so long as they follow these guidelines

  • The name for a component tag typically follows a CamelCasing convention

    • first letter of the component name must also have a capital letter

      • e.g. <AnotherApp />