Skip to content

Instantly share code, notes, and snippets.

@0bie
Last active June 21, 2018 09:57
Show Gist options
  • Save 0bie/57ea7c625199486d6aa2b2c3e8838d13 to your computer and use it in GitHub Desktop.
Save 0bie/57ea7c625199486d6aa2b2c3e8838d13 to your computer and use it in GitHub Desktop.
Beginner notes on React JS

React Notes 2

  • To prevent syntax repetition you can abstract common properties from the React object using ES6 Destructuring E.g:
//before
import React from 'react';

class Searchbar extends React.Component {
    static propTypes = {
        property1: React.PropTypes.string.isRequired,
        property2: React.PropTypes.any
    }
    static defaultProps = {
        property1: ''
    }
}

//after
import React, {Component, PropTypes} from 'react';

class Searchbar extends Component {
    static propTypes = {
        property1: PropTypes.string.isRequired,
        property2: PropTypes.any
    }
    static defaultProps = {
        property1: ''
    }
}

Functional Component

  • Similar to a function and returns jsx that gets rendered to the DOM
//Searchbar.js
const Searchbar = () => {
    return <input />;
};

//index.js
const App = () => {
    return (
        <div>
            <Searchbar />
        </div>
    );
}
  • In functional components the props object is passed as an argument E.g:
const App = (props) => { }

Class Component

  • Used whenever a component needs to have some kind of internal record keeping

  • It is self aware and keeps track of anything that happens to it once it has been rendered

  • It is created using an ES6 class

class Searchbar extends React.Component {
    render() {
        return <input />;
    }
}
  • By extending React.Component you give the Searchbar class added functionality (state and props)

  • To call an instance of a class you have to wrap it in jsx tags E.g: <Searchbar />

  • Start off with a functional component and as your component gets complex you can convert to a class

  • In a class component props are available within the component and don't need to be passed in as an argument. It can be accessed in a method using this.props

Event Handling

  • Similar to a regular event handler, in react it is a function that runs anytime an event occurs

  • In react you declare the event handler then pass it to the element that you want to monitor for events

  • It is considered best practice to begin the name of an event handler with on or handle E.g:

class Searchbar extends React.Component {
    handleInputChange(e) {
        console.log(e.target.value);
    }
    render() {
        return <input onChange={this.handleInputChange()} />;
    }
}

State

  • state is a plain javascript object that is used to record and react to user events

  • Each class based component has its own state object

  • Whenever state is changed a component re-renders and also forces all of its children to re-render as well

  • Before state can be used in a component the object needs to be initialized E.g:

class Searchbar extends React.Component {
    constructor(props) {
        super(props);
        this.state = { term: ''};
    }
    handleInputChange(e) {
        console.log(e.target.value);
    }
    render() {
        return <input onChange={this.handleInputChange()}/>;
    }
}
  • The constructor function is called whenever a new instance of a class is created

  • It is reserved for setting up certain configurations in a class such as initializing variables, initializing state or binding event handler methods

  • super is a reference to the constructor method on the React.Component class that is getting extended. This means that is has its own constructor function and so to reference it we have to use the super keyword

  • In the code above state has been initialized E.g: this.state = { property1: '' }

  • This syntax should only be used to declare state within the constructor function

  • this.setState() should be used to manipulate state after it has been initialized E.g this.setState({ property1: 'new state'});

class Searchbar extends React.Component {
    constructor(props) {
        super(props);
        this.state = { term: ''};
    }
    render() {
        return (
            <div>
                <input
                    value={this.state.term}
                    onChange={(e) => this.setState({term: e.target.value })} />
            </div>
        );
    }
}
  • In the code above the value of the input has been set to the state

  • This means that the component is declarative, the state determines how the data or UI is manipulated.

  • When an action (or change) occurs the component is already aware through its change in state and then re-renders

Downwards Data Flow

  • The most parent component (App) should be responsible for handling and fetching data in a react app E.g
class App extends Component {
    constructor(props) {
        super(props);

        this.state = { videos: []};

        YTSearch({key: API_KEY, term: 'react js'}, (videos) => {
            this.setState({ videos })
            //this.setSate({ videos: videos});
        });
    }
    render() {
        return (
            <div>
                <Searchbar />
                <VideoDetail />
                <VideoList />
            </div>
        );
    }
}
  • In the code above the YTSearch method is used to return a list of videos to a react app and this information is going to be used by multiple components

  • It makes sense to call that method on the constructor of the App component which is the parent in this case

  • This also makes it possible for every instance of the App to have that YTsearch API method available

  • To prevent syntax repetition you can make use of ES6 property value shorthand

  • E.g : In the code above when this.setState() is called within the callback function the videos arg (which is a variable) is the same as the initialized state (this.state = { videos: []}) so instead of repeating that variable you can use ES6 to set it as the current state: this.setState({ videos })

  • That is the same as saying : this.setState({ videos: videos})

More Examples
//js without ES6
function getCar(make, model, value ) {
    return {
        make: make ,
        model: model,
        value: value
    };
}

//with ES6
function getcar(make, model, value) {
    return {make, model, value};
}

Iterating Over Data

  • It is considered best practice to avoid the use of for loops in react

  • You should make use of built-in helpers such as the array map method E.g

//ES5
var array = [1, 2, 3];
array.map(function(number) { return number * 2});

//ES6
let array = [1, 2, 3];
array.map((number) => { number * 2});

Working with Strings

const VideoDetail = ({video}) => {
    // const video = props.video;

    const videoId = video.id.videoId;
    const url = `https://www.youtube.com/embed/${videoId}`;

    return (
        <iframe className="embed-responsive-item" src={url}></iframe>
    );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment