React essentials

summarizing the famous interface-building JavaScript library

notes2021-11-01 15:02

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:

1function App() {
2    const appName = "joncoded"
3    return (        
4        <div className="App">
5            <p>Welcome to ${appName}</p>
6        </div>
7    )
8}

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:

1import App from './App'
2
3function AnotherApp() {
4    return (
5        <>
6            <h1> Wrapper App </h1>
7            <App />
8        </>
9    )
10}

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 />