All Projects → vincsb → react-cheat-sheet

vincsb / react-cheat-sheet

Licence: other
📚 The perfect React Cheat Sheet for daily use with a lot of Javascript / JSX snippets !

Projects that are alternatives of or similar to react-cheat-sheet

react-pits
React 中的坑
Stars: ✭ 29 (-50.85%)
Mutual labels:  react-router, jsx, react-redux
spring-boot-react-ecommerce-app
eCommerce application based on the microservices architecture built using Spring Boot and ReactJS.
Stars: ✭ 221 (+274.58%)
Mutual labels:  react-router, react-redux
react-demo
一个实际项目(OA系统)中的部分功能。这个demo中引入了数据库,数据库使用了mongodb。安装mongodb才能运行完整的功能
Stars: ✭ 92 (+55.93%)
Mutual labels:  react-router, react-redux
rgxp
Regular Expression Collection (ReactJS, Redux, React Router, Recompose, NodeJS, Express)
Stars: ✭ 62 (+5.08%)
Mutual labels:  react-router, react-redux
Awesome Web Components
🤖 Awesome web components and snippets for every Front-End Developer
Stars: ✭ 28 (-52.54%)
Mutual labels:  snippets, front-end-development
role-based-access-control
Role-based authorization || Role-based access-control in React.js
Stars: ✭ 111 (+88.14%)
Mutual labels:  jsx, react-redux
ts-react-boilerplate
A very opinionated (React/TypeScript/Redux/etc) frontend boilerplate
Stars: ✭ 43 (-27.12%)
Mutual labels:  react-router, react-redux
React Sight
Visualization tool for React, with support for Fiber, Router (v4), and Redux
Stars: ✭ 2,716 (+4503.39%)
Mutual labels:  react-router, react-redux
react-calculator
📐 PWA React + Redux Calculator
Stars: ✭ 65 (+10.17%)
Mutual labels:  jsx, react-redux
cnode-react
a web app for cnode.org with react + react-router + react-redux
Stars: ✭ 23 (-61.02%)
Mutual labels:  react-router, react-redux
Questions
Web app inspired by Quora, allowing users ask question and get answers
Stars: ✭ 15 (-74.58%)
Mutual labels:  react-router, react-redux
Snippetstore
🎉 A snippet management app for developers 🚀
Stars: ✭ 762 (+1191.53%)
Mutual labels:  snippets, react-router
ant-design-snippets
ant-design-snippets
Stars: ✭ 18 (-69.49%)
Mutual labels:  snippets, react-redux
OpenTrivia
Multiplayer quiz game demo using React and Opentdb API
Stars: ✭ 47 (-20.34%)
Mutual labels:  react-router, react-redux
ReactEd
An extension to assist with development of react and redux applications.
Stars: ✭ 48 (-18.64%)
Mutual labels:  snippets, props
awesome-web-react
🚀 Awesome Web Based React 🚀 Develop online with React!
Stars: ✭ 31 (-47.46%)
Mutual labels:  react-router, react-redux
iwish
I wish that too!
Stars: ✭ 19 (-67.8%)
Mutual labels:  jsx, react-redux
Alldemo
🍑 2020全栈学习Demo大合集 包含最新 hooks TS 等 还有umi+dva,数据可视化等实战项目 (持续更新中)
Stars: ✭ 189 (+220.34%)
Mutual labels:  react-router, react-redux
Imooc React
慕课网 React 视频课程源代码
Stars: ✭ 203 (+244.07%)
Mutual labels:  react-router, react-redux
React-Netflix-Clone
A Fully Responsive clone of Netflix website built using React.JS as a Front-end & Firebase as a Back-end.
Stars: ✭ 91 (+54.24%)
Mutual labels:  react-router, jsx

📚 React Cheat Sheet

This repository is a cheat sheet to React for daily use. It contain a lot of snippets from my own use / official documentation and i'll improve it soon !
It's made for people like me who like to continue have a overview of some snippets.

Table of Contents

  1. React
  2. Redux

1 - React

Use React

// Import React and ReactDOM
import React from 'react'
import ReactDOM from 'react-dom'
// Render JSX into a DOM element
ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);
// Render Component into a DOM element
ReactDOM.render(
  <MyComponent />,
  document.getElementById('root')
);

Go to top

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 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 tag is empty
const item = <div />;

Go to top

Components

// Stateless Functional Component
function Heading(props) {
  return <h1>{props.title}</h1>;
}
// Stateless Functional Component (with arrow function)
const Heading = (props) => {
  return <h1>{props.title}</h1>;
}
// ES6 Class Component, can have states
class Heading extends React.Component {
  render() {
    return <h1>{this.props.title}</h1>;
  }
}
// Always start component names with capital
<Heading />

Go to top

Render

// Return React Element
render() {
  return <div>Example of return<div />
}
// Return Another Component
render() {
  return <MyComponent />
}
// Return String
render() {
  return 'Return a string works!'
}
// Return Numbers (rendered as text node)
render() {
  return 100
}
// Return nothing
render() {
  return null
}

Go to top

Component Lifecycle

componentWillMount() {

}
componentDidMount() {
  // Call after the component output has been rendered in the DOM
}
componentWillReceiveProps() {

}
shouldComponentUpdate() {

}
componentWillUpdate() {

}
componentDidUpdate() {

}
componentWillUnmount() {

}
componentDidCatch() {

}

Go to top

Props (Properties)

Props are immutable.

// Component with a single valid argument : props
function Heading(props) {
  return <h1>{props.title}</h1>;
}

Go to top

State

State are locals and fully controlled by the component itself.

// Update state with setState, except in constructor
this.setState({
  title: 'Updated title',
});
// Set state with previous state
this.setState((prevState, props) => {
  return {count: prevState.count + 1};
});
// Declare initial state in constructor
class Heading extends React.Component {
  constructor(props) {
    super(props);
    this.state = {title: 'My title'};
  }
}
// Do not update state directly
this.state.title = 'Hello';
// Lifting state up to share state between component
class Wrapper extends React.Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.state = {value: ''};
  }

  handleInputChange(value) {
    this.setState({value});
  }
  render() {
    const value = this.state.value;
    return (
        <Input value={value} onInputChange={this.handleInputChange} />
    );
  }
}

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onInputChange(e.target.value);
  }

  render() {
    const value = this.props.value;
    return <input value={value} onChange={this.handleChange} />;
  }
}

Go to top

Handling Event

// React Event are in camelCase
<button onClick={handleClick}>
  Action
</button>
// Use preventDefault instead of return false
function handleClick(e) {
  e.preventDefault();
}
// Bind this to use it in the callback
constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this);
}
// Pass data to callback
<button onClick={(e) => this.deleteItem(id, e)}>Delete item</button>
<button onClick={this.deleteItem.bind(this, id)}>Delete item</button>

Go to top

Conditional Rendering

// Using if operator with props
function Heading(props) {
  const isHome = props.isHome;
  if (isHome) {
    return <HomeHeading />;
  }
  return <PageHeading />;
}
// Using if operator with state
render() {
  const isHome = this.state.isHome;
  let heading = null;
  if (isHome) {
    heading = <HomeHeading />;
  } else {
    heading = <PageHeading />;
  }

  return (
    <div>
      {heading}
    </div>
  );
}
// Using ternary operator
<div>
  {isHome ? <HomeHeading /> : <PageHeading />}
</div>
// Using logical operator
<div>
  {messages.length > 0 &&
    <h1>
      You have messages
    </h1>
  }
</div>
// Prevent component from rendering
function Modal(props) {
  if (!props.isShow) {
    return null;
  }

  return (
    <div>
      Modal
    </div>
  );
}

Go to top

Portal

import { createPortal } from "react-dom";

class MyPortalComponent extends React.Component {
  render() {
    return createPortal(
      this.props.children,
      document.getElementById("node"),
    );
  }
}

Go to top

Fragment

const Fragment = React.Fragment;

render() {
  return (
    <Fragment>
      Some text.
      <h2>A heading</h2>
      Even more text.
    </Fragment>
  );
}
render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
      Even more text.
    <React.Fragment>
  );
}
render() {
  return (
    <>
      <ComponentA />
      <ComponentB />
    </>
  );
}

Go to top

Forms

Controlled Components

// In controlled component, each state mutation have an handler function
class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  handleSubmit(e) {
    alert('Submitted value: ' + this.state.value);
    e.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
// Force to uppercase in handler
handleChange(e) {
  this.setState({value: e.target.value.toUpperCase()});
}
// <textarea> in React use a value attribute
<textarea value={this.state.value} onChange={this.handleChange} />
// <select> use a value and not a selected attribute
<select value={this.state.value} onChange={this.handleChange}>
  <option value="a">Option A</option>
  <option value="b">Option B</option>
</select>
// <select value can have an array for multiple values
<select multiple={true} value={['a', 'b']}>
// Handle multiple inputs with name attribute
handleInputChange(e) {
  const target = e.target;
  const value = target.value;
  const name = target.name;

  this.setState({
    [name]: value
  });
}

render() {
  return (
    <form>
      <input name="firstName" onChange={this.handleInputChange} />
      <input name="lastName" onChange={this.handleInputChange} />
    </form>
  );
}

Go to top

React without JSX

// This two elements are similar :
const element = (
  <h1 className="heading">
    Hello!
  </h1>
);

const element = React.createElement(
  'h1',
  {className: 'heading'},
  'Hello!'
);

Go to top

Typechecking props with PropTypes

// Use PropTypes
import PropTypes from 'prop-types';
// Prop is an optional array
MyComponent.propTypes = {
  optionalArray: PropTypes.array,
};
// Prop is an optional boolean
MyComponent.propTypes = {
  optionalBool: PropTypes.bool,
};
// Prop is an optional function
MyComponent.propTypes = {
  optionalFunc: PropTypes.func,
};
// Prop is an optional number (integer, float...)
MyComponent.propTypes = {
  optionalNumber: PropTypes.number,
};
// Prop is an optional object
MyComponent.propTypes = {
  optionalObject: PropTypes.object,
};
// Prop is an optional string
MyComponent.propTypes = {
  optionalString: PropTypes.string,
};
// Prop is an optional symbol
MyComponent.propTypes = {
  optionalSymbol: PropTypes.symbol,
};
// Prop is an optional node (numbers, strings, elements, array, fragment)
MyComponent.propTypes = {
  optionalNode: PropTypes.node,
};

Go to top

Create React App

# Create new app
create-react-app my-app

Go to top

Fetch datas

// Use componentDidMount hook with fetch
class PostsList extends Component {
  constructor(props) {
    super(props);
    this.state = {posts: []};
  }

  componentDidMount() {
    fetch('https://example.com/posts')
      .then(response => response.json())
      .then(data => this.setState({ posts: data.posts }));
      .catch(error => console.log(error));
  }
}
// Use Axios library to fetch datas
import axios from 'axios';

componentDidMount() {
  axios.get('/post', {
    params: {ID: 123}
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

Go to top

2 - Redux

Install Redux

npm install --save redux
# Install react binding
npm install --save react-redux
# Install dev tools
npm install --save-dev redux-devtools

Actions

// Declare action type
const SUBMIT_FORM = 'SUBMIT_FORM'
// Action shape with payload
{
  type: SUBMIT_FORM,
  payload: {
    firstName: 'John',
    lastName: 'Doe',
  }
}
// Action shape without payload
{
  type: SUBMIT_FORM,
}
// Declare action creator
function submitForm(formData) {
  return {
    type: SUBMIT_FORM,
    payload: {
      firstName: formData.firstName,
      lastName: formData.lastName,
    }
  }
}

Reducers

// Declare an initial state
const initialState = {
  firstName: '',
  lastName: '',
  city: '',
}
// Declare a minimal reducer
function userReducer(state = initialState, action) {
  return state;
}
// Handle action in reducer
function userReducer(state = initialState, action) {
  switch (action.type) {
   case SUBMIT_FORM:
     return {
       ...state,
       firstName: action.payload.firstName,
       lastName: action.payload.lastName,
       city: action.payload.city,
     };
   default:
     return state;
 }
}

Go to top

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].