Skip to content

Instantly share code, notes, and snippets.

@1UC1F3R616
Last active January 13, 2022 10:28
Show Gist options
  • Save 1UC1F3R616/fc358492ca393719c56b339df45f9c43 to your computer and use it in GitHub Desktop.
Save 1UC1F3R616/fc358492ca393719c56b339df45f9c43 to your computer and use it in GitHub Desktop.

npx create-react-app myapp

// Import the React and ReactDOM libraries
// Create a react component
// Take the react component and show it on the screen
- setting states in Class based component is done by simply `state = { var1: [], var2: 'value' }`
- Do not set state 2nd time instead alter the only declaration
- State change is done like this `this.setState({var2: null})`
- to pass props inside a component from top to bottom --> `<componentName myProp={key1: value}>`
- To access the props --> (props) => {return <div>props.key1</div>}
- You can use destrcturing

Simple index.js (Functional Based)

// Import the React and ReactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Create a react component
const App = () => {
    return <div>Hi There!</div>
}

// Take the react component and show it on the screen
ReactDOM.render(
    <App />, document.querySelector('#root')
);

Adding Components

  • CommentDetail is a function that has JSX inside it and it is imported from another file
const App = () => {
    return (
        <div className="ui container comments">
            <CommentDetail />
            <CommentDetail />
            <CommentDetail author="Kush" />
        </div>
    );
};

Simple index.js (Class Based)

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
    
    render() {
        window.navigator.geolocation.getCurrentPosition(
            (position) => console.log(position),
            (err) => console.log(err)
        )
        return <div>Latitude: </div>
    }
}

ReactDOM.render(
    <App />,
    document.querySelector('#root')
)

Simple Example using States and Conditional rendering

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
    // Initializing State
    constructor(props) {
        super(props);

        // only time we do direct assignment
        this.state = { lat: null, errorMessage: '' };

        window.navigator.geolocation.getCurrentPosition(
            (position) => {
                this.setState({lat: position.coords.latitude})},
            (err) => {
                this.setState({errorMessage: err.message})
            }
        )
    }
    
    render() {
        if (this.state.errorMessage && !this.state.lat) {
            return <div>Error: { this.state.errorMessage }</div>
        } else if (!this.state.errorMessage && this.state.lat) {
            return <div>Lat: {this.state.lat}</div>
        } else {
             return (
                <div>
                Latitude: { this.state.lat }
                <br/>
                Error: { this.state.errorMessage }
                </div>
                );
        }

    }
}

ReactDOM.render(
    <App />,
    document.querySelector('#root')
)

Component Lifecycle

  constructor (good place to do one-time setup)
    ⬇
  render (Avoid doing anything beside returning JSX)
  `content visible on screen`
    ⬇
  componentDidMount (good place to do data loading)
  `Sit and wait for updates...`
    ⬇
  componentDidUpdate (Good place to do more data-loading when state/props change)
  `Sit and wait until this component is not longer shown`
    ⬇
   componentWillUnmount (Good place to do cleanup, especially for non-React stuff)

Other lifecycle methods (rarely used)

  • shouldComponentUpdate
  • getDerivedStateFromProps
  • getSnapshotBeforeUpdate

Event Handlers: Handling events with React elements is very similar to handling events on DOM elements

  • onClick User clicks on something : A div can be clicked
  • onChange User changes text in an input
  • onSubmit User submits a form

React Refs

  • Gives access to a single DOM element
  • We create refs in the constructor -> Assign them to instance variables -> then pass to a particular JSX element as props

React Hooks

Hooks System

  • useState: Function that lets you use state in a functional component
  • useEffect: Function that lets you use something like lifecycle methods in a functional component
  • useRef: Function that lets you create a ref in a funcitonal component

Hooks are way to write resuable code, instead of more classic techniques like inheritance

10 Primitive Hooks (Not a Technical term)

  • useState
  • useEffect
  • useContext
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

Custom Hook (Example)

  • useTranslate
    • useState
    • useEffect

Class Components v/s Function Components

- Class Components Function Components
Initalization state = { activeIndex: 0 } useState(0)
Refernce this.state.activeIndex activeIndex
Updates this.setState({ activeIndex: 10 }) setActiveIndex(10)

Examples are added in comments


Redux

  • React is to render and present data to user not handling

What is Redux?

  • State Managment Library
  • Makes creating complex applications easier
  • Not required to create a React App!
  • Not explicitly designed to work with React!

Redux Cycle

Action Creator
    ⬇
Action
    ⬇
Dispatch
    ⬇
Reducers
    ⬇
State
@1UC1F3R616
Copy link
Author

React Hook using State Example

import React, { useState } from "react";

const Accordion = ({ items }) => {
    const [activeIndex, setActiveIndex] = useState(null);

    const onTitleClick = (index) => {
        setActiveIndex(index);
    };

    const renderedItems = items.map((item, index) => {
        return (
            <React.Fragment key={item.title}>
                <div
                    className="title active"
                    onClick={() => onTitleClick(index)}
                >
                    <i className="dropdown icon"></i>
                    {item.title}
                </div>
                <div className="content active">
                    <p>{item.content}</p>
                </div>
            </React.Fragment>
        );
    });

    return (
        <div className="ui style accordion">
            {renderedItems}
            <h1>{activeIndex}</h1>
        </div>
    );
};

export default Accordion;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment