Introduction to React

A JavaScript library for building user interfaces.

These are my notes from learning React.

If you don’t care about my notes skip to the sources at the end of the article.

Prerequisites

To understand my notes you will need basic knowledge of HTML and JavaScript (ES6). If you want to refresh your knowledge of JS check out my notes.

You will also need Node.js and NPM.

About React

React is a declarative, efficient, and flexible COMPONENT BASED JavaScript library for building user interfaces. React processes only user interfaces in applications. It was developed by engineers at Facebook.

Reasons to use React

  • Speed – Apps made in React can handle complex updates and still feel quick and responsive.
  • Modularity –  Instead of writing large, dense files of code, you can write many smaller, reusable files.
  • Scalability – Large programs that display a lot of changing data are where React performs best.
  • Flexibility – You can use React for interesting projects that have nothing to do with making a web app. People are still figuring out React’s potential. There’s room to explore.
  • Popularity – While this reason has admittedly little to do with React’s quality, the truth is that understanding React will make you more employable.

How to install

There are different ways to install React, I prefer using NPM andcreate-react-app

create-react-app

If you’re getting started with React, use create-react-app to automate the build of your app. There is no configuration file, and react-scripts is the only extra build dependency in your package.json. Your environment will have everything you need to build a modern React app:

  • React, JSX, ES6, and Flow syntax support.
  • Language extras beyond ES6 like the object spread operator.
  • A dev server that lints for common errors.
  • Import CSS and image files directly from JavaScript.
  • Autoprefixed CSS, so you don’t need -webkit or other prefixes.
  • build script to bundle JS, CSS, and images for production, with sourcemaps
npm install -g create-react-app

create-react-app my-app
cd my-app/
npm start

It will create a directory called my-app inside the current folder.
Inside that directory, it will generate the initial project structure and install the transitive dependencies:

my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   └── favicon.ico
│   └── index.html
│   └── manifest.json
└── src
    └── App.css
    └── App.js
    └── App.test.js
    └── index.css
    └── index.js
    └── logo.svg
    └── registerServiceWorker.js

The basics

JSX

reactjs-yo-dawg-i-heard-you-like-xml-so-we-put-xml-in-your-js-so-you-can-xml-while-you-html

JSX stands for JavaScript XML. It is a syntax extension to JavaScript. JSX produces React “elements”. After compilation, JSX expressions become regular JavaScript objects.

const element = <h1>Hello, world!</h1>;

You can embed any JavaScript expression in JSX by wrapping it in curly braces.

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

ReactDOM.render(
  element,
  document.getElementById('root')
);

JSX Represents Objects

Babel compiles JSX down to React.createElement() calls.

These two examples are identical:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

Rendering elements

Elements are the smallest building blocks of React apps.

An element describes what you want to see on the screen:

const element = <h1>Hello, world</h1>;

ReactDOM.render(
element,
document.getElementById('root')
);

Unlike browser DOM elements, React elements are plain objects, and are cheap to create.

React DOM takes care of updating the DOM to match the React elements. 

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

Components

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. More about components can be found here.

// class component - es6 style
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
// functional component
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
//rendering component
const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

Composing components

Components can refer to other components in their output.

For example, we can create an App component that renders Welcome many times:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Don’t be afraid to split components into smaller components.

Props

When we use our defined components, we can add attributes called props. These attributes are available in our component as this.props and can be used in our render method to render dynamic data:

var MyComponent = React.createClass({
    render: function(){
        return (
            <h1>Hello, {this.props.name}!</h1>
        );
    }
});

React.render(<MyComponent name="Handsome" />, document.getElementById('myDiv'));

State

Every component has a state object and a props object. State is set using the setStatemethod. Calling setState triggers UI updates and is the bread and butter of React’s interactivity. If we want to set an initial state before any interaction occurs we can use the getInitialState method.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()}; // this is valid in constructor, elsewhere use setState()
  }

  render() {
    return (
     <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

Lifecycle methods

Here are some lifecycle methods in React you should know:

  • componentWillMount – Invoked once, on both client & server before rendering occurs.
  • componentDidMount – Invoked once, only on the client, after rendering occurs.
  • shouldComponentUpdate – Return value determines whether component should update.
  • componentWillUnmount – Invoked prior to unmounting component.

Handling Events

React also has a built in cross browser events system. The events are attached as properties of components and can trigger methods.

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

Conclusion

Hope you enjoyed! There are still tons of things that I want to cover in my next posts.

In my next article, I will show you how to start a React project and program simple TODO application.

Sources

https://reactjs.org/docs

https://scotch.io/tutorials/learning-react-getting-started-and-concepts

https://reactjs.org/tutorial/tutorial.html

https://reactjs.org/docs/react-component.html

https://www.udemy.com/react-redux/