react_basic
Basics
JSX
JSX is a syntax extension to JavaScript, it combines js with html, it only comes in when writes your js code like this, but not all browsers support such extension, if browser does not support it, you can convert it to native js code by Babel at server-side or at client side by include Babel.js for that website, we recommend do this in server-side as we can do some optimization. but Most mordent browsers support JSX now.
1 | const element = <h1 className="greating"> Hello </h1>; |
Embedding Expressions in JSX
You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.
1 | const name = 'Josh Perez'; |
React DOM uses camelCase property naming convention instead of HTML attribute names
- class becomes className in JSX, and tabindex becomes tabIndex
- built-in tag attributes may be renamed if it has two words or one word that is reserved by JSX
There are several rules about JSX
<tags> are elements
- JSX <tags> map to calls to React.createElement().
- Use <lowercase /> tags when you need a DOM elements, and
tags for component elements
JSX children become child elements
- they become the element’s props.children
Attributes are props
- Use “” quotes when your props are strings
- Use {} braces when your props are literals or variables
{} interpolates children
- When a pair of {} braces is encountered within a JSX element, it’s value will be interpolated in as a child.
- let Hello = (props) => <div>Hello, {props.to}
Empty <> tags
- A pair of empty <> and </> tags get’s turned into a React.Fragment element, i.e. an element that doesn’t map to DOM nodes
{…object} acts like Object.assign()
- Passing {…object} as an attribute will add all of the properties of the object as separate attributes
Function Component
Function Component has no state, is cheap, always use it if no state needed or no life cycle hooks needed.
Function Component must return a React element or null to prevent render there are several ways to achieve this.
Actually you can use any name to replace props but props seems have the right meaning
. any object name would be fine.
1 | function Welcome(props) { |
props check and default value
When we declare an property of an React element, we can add some checks and default value for it.
1 | import PropTypes from 'prop-types'; |
Note this way also works for Class Component as well!!!
More step of function component.
As normally, Function Component is not stateful or no lifecycle hook like Class Component, but class Component is heavy, is there a way we can use state and lifecycle hook like Class does. that’s why Hooks comes into place which let you use state and other React features without writing a class(use them in Function.
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes.
State Hook
1 | import React, { useState } from 'react'; |
useState is a Hook. We call it inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together
Effect Hook
The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API
.
1 | import React, { useState, useEffect } from 'react'; |
Effects are declared inside the component so they have access to its props and state. By default, React runs the effects after every render — including the first render
.
Rules for Hooks
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.
Class Component
Class Component has a built-in state attribute, an object stores all states of such component, it must - inherit from React.Component
- call super(props) if has custom constructor, you can also access this.props in its method!!!
- have a render() method that returns an React element
1 | class Clock extends React.Component { |
React element life cycle hooks
When we mount a React element to a Dom node(mount point), other remove it from that, several event happens, React already added some hooks to each event, you just need to implement that hook if you want to do thing.
1 | class Clock extends React.Component { |
Data(state) Flow Down
state is often called local or encapsulated, always set it and access it in the component who owns it, if child wants to access it, pass it as props to the child.
Lift state up
Two child elements wants to modify same state(shared same one), this is impossible if each child has a state as it’s local so lift state up, after Lift state up, parent elements owns this state, that means parent is only person who can call setState to update it, but two children want to modify it and see same, so parent passes two props to child, one is the value, the other is callback defined by parent, each child calls the callback which setState() to update the shared state which owns by parent. child update parent’s state by parent’s callback.
1 | class AButton extends React.Component { |
Composition vs Inheritance
We recommend using composition instead of inheritance to reuse code between components, here are some good example to use composition
1 | function FancyBorder(props) { |
Controlled Component
In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state
and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the React state be the “single source of truth”
. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”
. React does not want HTML dom element maintain their own state, React wants state be ‘single source of truth’, that why React wants to control the value(state property).
1 | class NameForm extends React.Component { |
Uncontrolled component
1 | class NameForm extends React.Component { |
React Events
React implements the standard Event API(W3C Spec) that’s same as Dom event except React named with different styles.
- React events are named using camelCase, rather than lowercase
- With JSX you pass a function as the event handler, rather than a string.
In html1
2
3<button onclick="activateLasers()">
Activate Lasers
</button>
In React
1 | <button onClick={activateLasers}> Activate Lasers |
Note: if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method otherwise you can’t use this in that handler
1 | //*experimental* |
Another difference is that you cannot return false to prevent default behavior in React. You must call preventDefault explicitly.
{} treats special handling for Array
As you know any expression can be in {}, if an Array in the {}, it will destruct the Array!! also note when use map, each item must has a key attribute, this is required by React.
1 | function NumberList(props) { |
Fragments
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM
1 | class Columns extends React.Component { |
Use CSS module
CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format
this is done Webpack, it let you use the same CSS class name in different files
without worrying about naming clashes, you write CSS files like before, nothing change for you when writing CSS file.
1 | //button.css |
1 | //text.css |
1 | //use it in react app Button.js |
The result in html is this
1 | <!-- This button has red background but not red text --> |