Skip to content
Search

React:Component

lastmod 2023-06-09created 2022-11-1515 edits

How to write components in React.

Function components

Defined with function, returning JSX code in the return statement.

import React from "react";
import "./App.css";

function NameBox() {
  const name = "test";
  return <div>{name}</div>;
}

export default NameBox;

A function component can also be defined with an arrow function instead of function.

import React from "react";
import "./App.css";

const NameBox = () => {
  const name = "test";
  return <div>{name}</div>;
};

export default NameBox;

Class components

Defined with class, returning JSX code from the render() function.

import React, { Component } from "react";

class NameBox extends Component {
  render() {
    const name = "react";
    return <div className="react">{name}</div>;
  }
}

export default NameBox;

Props vs State

Props in TypeScript

defaultProps

Setting it outside the class:

import React, { Component, Fragment } from 'react'

export default class Hello extends Component {
    // ...
}

Hello.defaultProps = {
    name:"초기값"
}

Setting it inside the class:

import React, { Component, Fragment } from 'react'

export default class Hello extends Component {
    static defaultProps = {
        name:"초기값"
    }
    // ...
}

Event handling

Passing Elements to a component

This corresponds to slots in Vue. Use a children prop of type React:ReactElement or React:ReactNode.

import React from 'react';

type BoxProps = {
  name: string;
  country: string;
  children: React.ReactNode;
};

// 👇️ using React.FunctionComponent
const Box: React.FunctionComponent<BoxProps> = ({name, country, children}) => {
  return (
    <div>
      <h1>{name}</h1>
      <h1>{country}</h1>
      {children}
    </div>
  );
};

const App = () => {
  return (
    <div>
      <Box name="James Doe" country="Germany">
        <h1>Hello</h1>
        <h1>World</h1>
      </Box>
    </div>
  );
};

export default App;

React component lifecycle

Some lifecycle methods are used in class components and are not available in function components, but similar functionality is achieved with Hooks.

mount

  • The DOM is created and then appears in the web browser.

update

  • When the component's props change
  • When state changes
  • When the parent component re-renders
  • When rendering is forced with this.forceUpdate

unmount

  • Only class component
  • The reverse of mounting. The process of removing a component from the DOM.

render

  • Called after mounting
  • This method defines what the component looks like and has always appeared in class components. It is the only required method among the lifecycle methods. It renders the prepared UI.

Caveats

  • Inside this method you can access this.props and this.state; it returns a React element
  • Inside this method, do not use setState outside of event setup
  • Do not access the browser DOM directly; if you want to read DOM information or change state, do it in the componentDidMount method

getDerivedStateFromProps

  • A new method added in React 16.3
  • Used to synchronize values received through props into state.
  • Called when the component mounts and updates.

componentDidMount method

  • componentDidMount and useEffect
  • A method that runs after the component is created and the first render is complete
  • Calls to other JavaScript library or framework functions, and asynchronous tasks such as setInterval, event registration, and network requests, are handled in this method.

shouldComponentUpdate

  • Specifies whether to start re-rendering the component when props or state change.
  • This method must return true or false.
  • If this method is not defined when creating the component, it returns true by default.
  • Inside this method, the current props and state are accessible as this.props and this.state.
  • The props and state about to be set are accessible as nextProps and nextState respectively.
  • When optimizing the performance of the whole project, it can return false to prevent re-rendering where appropriate.
  • In other words, this method can be used for performance optimization.

getSnapshotBeforeUpdate

  • A new method added in React 16.3
  • Called right before the output of render is actually reflected in the browser.
  • The value this method returns can be received as snapshot, the third parameter of the #componentDidUpdate method described below,
  • and it is mainly used when you need to refer to values from just before the update. (EX: preserving the scrollbar position)

componentDidUpdate

  • A method that runs after re-rendering is complete; since the update has just finished, it is safe to do DOM-related work.
  • Here you can use prevProps and prevState to access the data the component had before, and this method can receive the value returned from the #getSnapshotBeforeUpdate method described above.
  • componentDidUpdate(prevProps, prevStae, snapshot) { … }

componentWillUnmount

  • A method that runs when the component is removed from the DOM;
  • events, timers, and manually created DOM registered in #componentDidMount must be removed here.

componentDidCatch

  • A new method added in React 16;
  • when an error occurs during component rendering, it shows an error UI instead of freezing.
componentDidCatch(error, info) {
    this.setState({
        error: true
    });
    console.log({error, info});
}
  • error receives which error occurred,
  • info receives information about where in the code the error occurred.

This method cannot catch errors in its own component; it can only catch errors that occur in components passed through its this.props.children.

See also

Favorite site

author Zer0 sitemap