DEV Community

kim
kim

Posted on

1 2

React Cheat Sheet

Below are the React Component and Elements Cheat Sheets.
Read full cheat sheet at React Cheat Sheet

1. React Component Lifecycle

Each component in React has a lifecycle that you can monitor and manipulate during its three main phases

React Mounting

  • constructor(): called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values.

Example:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  render() {
    return (
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
  • getDerivedStateFromProps(): Called right before rendering the element(s) in the DOM

Example:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritefood: props.favfood };
  }
  render() {
    return (
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
    );
  }
}

ReactDOM.render(<Header favfood="hotdog"/>, document.getElementById('root'));
  • render(): required, and is the method that actually outputs HTML to the DOM.

Example

class Header extends React.Component {
  render() {
    return (
      <h1>This is the demo content</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
  • componentDidMount(): called after the component is rendered.

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritefood: "hotdog"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
    );
  }
}

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

React Updating

  • getDerivedStateFromProps(): This is the first method that is called when a component gets updated.

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritefood: props.favfood };
  }
  changeFood = () => {
    this.setState({favoritefood: "sushi"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
      <button type="button" onClick={this.changeFood}>Change food</button>
      </div>
    );
  }
}

ReactDOM.render(<Header favfood="hotdog"/>, document.getElementById('root'));
  • shouldComponentUpdate(): you can return a Boolean value that specifies whether React should continue with the rendering or not.

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeFood = () => {
    this.setState({favoritefood: "sushi"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
      <button type="button" onClick={this.changeFood}>Change food</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
  • render(): called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  changeColor = () => {
    this.setState({favoritefood: "sushi"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
      <button type="button" onClick={this.changeFood}>Change food</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
  • getSnapshotBeforeUpdate(): you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritefood: "hotdog"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "When I was young, my favorite food is " + prevState.favoritefood;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "And now, my favorite food is " + this.state.favoritefood;
  }
  render() {
    return (
      <div>
        <h1>My Favorite Food is {this.state.favoritefood}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
  • componentDidUpdate(): called after the component is updated in the DOM.

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritefood: "pizza"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritefood: "hotdog"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "When I was young, my favorite food is " + this.state.favoritefood;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Food is {this.state.favoritefood}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

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

Unmounting

componentWillUnmount(): called when the component is about to be removed from the DOM.

Example

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Child />;
    };
    return (
      <div>
      {myheader}
      <button type="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}

class Child extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

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

2. React Elements and JSX

JSX produce React Element

const item = <h1>My JSX Element</h1>;

Use curly braces to embed some Javascript

const item = <div>{getContent()}</div>;

Use camelCase for the attribute name

 const item = <div className="example"></div>;

Use curly braces to embed some Javascript

const item = <img src={image.url}></img>;

Self-close if the tag is empty

const item = <div />;

Continue...

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay