Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

NotificationsYou must be signed in to change notification settings

vincsb/react-cheat-sheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation

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 ReactDOMimportReactfrom'react'importReactDOMfrom'react-dom'
// Render JSX into a DOM elementReactDOM.render(<h1>Hello, world!</h1>,document.getElementById('root'));
// Render Component into a DOM elementReactDOM.render(<MyComponent/>,document.getElementById('root'));

⬆ Go to top

JSX

// JSX produce React Elementconstitem=<h1>My JSX Element</h1>;
// Use curly braces to embed some Javascriptconstitem=<div>{getContent()}</div>;
// Use camelCase for attribute nameconstitem=<divclassName="example"></div>;
// Use curly braces to embed some Javascriptconstitem=<imgsrc={image.url}></img>;
// Self close if tag is emptyconstitem=<div/>;

⬆ Go to top

Components

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

⬆ Go to top

Render

// Return React Elementrender(){return<div>Example of return<div/>}
// Return Another Componentrender(){return<MyComponent/>}
// Return Stringrender(){return'Return a string works!'}
// Return Numbers (rendered as text node)render(){return100}
// Return nothingrender(){returnnull}

⬆ 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 : propsfunctionHeading(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 constructorthis.setState({title:'Updated title',});
// Set state with previous statethis.setState((prevState,props)=>{return{count:prevState.count+1};});
// Declare initial state in constructorclassHeadingextendsReact.Component{constructor(props){super(props);this.state={title:'My title'};}}
// Do not update state directlythis.state.title='Hello';
// Lifting state up to share state between componentclassWrapperextendsReact.Component{constructor(props){super(props);this.handleInputChange=this.handleInputChange.bind(this);this.state={value:''};}handleInputChange(value){this.setState({value});}render(){constvalue=this.state.value;return(<Inputvalue={value}onInputChange={this.handleInputChange}/>);}}classInputextendsReact.Component{constructor(props){super(props);this.handleChange=this.handleChange.bind(this);}handleChange(e){this.props.onInputChange(e.target.value);}render(){constvalue=this.props.value;return<inputvalue={value}onChange={this.handleChange}/>;}}

⬆ Go to top

Handling Event

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

⬆ Go to top

Conditional Rendering

// Using if operator with propsfunctionHeading(props){constisHome=props.isHome;if(isHome){return<HomeHeading/>;}return<PageHeading/>;}
// Using if operator with staterender(){constisHome=this.state.isHome;letheading=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 renderingfunctionModal(props){if(!props.isShow){returnnull;}return(<div>      Modal</div>);}

⬆ Go to top

Portal

import{createPortal}from"react-dom";classMyPortalComponentextendsReact.Component{render(){returncreatePortal(this.props.children,document.getElementById("node"),);}}

⬆ Go to top

Fragment

constFragment=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 functionclassFormextendsReact.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(<formonSubmit={this.handleSubmit}><inputtype="text"value={this.state.value}onChange={this.handleChange}/><inputtype="submit"value="Submit"/></form>);}}
// Force to uppercase in handlerhandleChange(e){this.setState({value:e.target.value.toUpperCase()});}
// <textarea> in React use a value attribute<textareavalue={this.state.value}onChange={this.handleChange}/>
// <select> use a value and not a selected attribute<selectvalue={this.state.value}onChange={this.handleChange}><optionvalue="a">Option A</option><optionvalue="b">Option B</option></select>
// <select value can have an array for multiple values<selectmultiple={true}value={['a','b']}>
// Handle multiple inputs with name attributehandleInputChange(e){consttarget=e.target;constvalue=target.value;constname=target.name;this.setState({[name]:value});}render(){return(<form><inputname="firstName"onChange={this.handleInputChange}/><inputname="lastName"onChange={this.handleInputChange}/></form>);}

⬆ Go to top

React without JSX

// This two elements are similar :constelement=(<h1className="heading">    Hello!</h1>);constelement=React.createElement('h1',{className:'heading'},'Hello!');

⬆ Go to top

Typechecking props with PropTypes

// Use PropTypesimportPropTypesfrom'prop-types';
// Prop is an optional arrayMyComponent.propTypes={optionalArray:PropTypes.array,};
// Prop is an optional booleanMyComponent.propTypes={optionalBool:PropTypes.bool,};
// Prop is an optional functionMyComponent.propTypes={optionalFunc:PropTypes.func,};
// Prop is an optional number (integer, float...)MyComponent.propTypes={optionalNumber:PropTypes.number,};
// Prop is an optional objectMyComponent.propTypes={optionalObject:PropTypes.object,};
// Prop is an optional stringMyComponent.propTypes={optionalString:PropTypes.string,};
// Prop is an optional symbolMyComponent.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 appcreate-react-app my-app

⬆ Go to top

Fetch datas

// Use componentDidMount hook with fetchclassPostsListextendsComponent{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 datasimportaxiosfrom'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 bindingnpm install --save react-redux# Install dev toolsnpm install --save-dev redux-devtools

Actions

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

Reducers

// Declare an initial stateconstinitialState={firstName:'',lastName:'',city:'',}
// Declare a minimal reducerfunctionuserReducer(state=initialState,action){returnstate;}
// Handle action in reducerfunctionuserReducer(state=initialState,action){switch(action.type){caseSUBMIT_FORM:return{       ...state,firstName:action.payload.firstName,lastName:action.payload.lastName,city:action.payload.city,};default:returnstate;}}

⬆ Go to top

About

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

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp