gintas.io

React reminder

December 27, 2018

Lately I have been learning React. Figured I would write down a small ‘cheatsheet’ of the basics. I find this type of code snippets useful when I come back to a certain programming language or a framework I have not used in a while. Consider making something similar when you are learning new skills, it helps memorizing!

End result:

Screen recording of the result

import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App";

ReactDOM.render(
    <App description={'This is description.'}/>,
    document.querySelector('#root')
);
import React from 'react';

class App extends React.Component {

    constructor(props) {
        //when extending constructor, you must call super(props)
        super(props);

        // initialize state
        this.state = {magicNumber: 999, width: 250, height: 150};

        this.updateRef = React.createRef();
    }

    componentDidMount() {
        // setting state outside of constructor can only be done using setState method
        // single variables can be updated without recreating the whole state object
        // updating state will force the component to re-render
        this.setState({magicNumber: 0});

        setInterval(()=>{
            // update the value of reference
            this.updateRef.current.innerHTML = new Date().getSeconds();
        }, 1000);
    }

    incrementMagicNumber() {
        this.setState({magicNumber: this.state.magicNumber+1});
    }


    render() {
        const list = [1, 2, 3].map((item) => <li key={item} >Number: {item}</li>);

        return (
            <div>
                <h1>Hello World!</h1>
                <p>
                    {this.props.description}<br/>
                    // assign reference
                    <b ref={this.updateRef} style={{fontSize: '64px'}}/>

                </p>

                <ul>{list}</ul>

                <button
                    // class should be named className
                    className={'magic-button'}
                    // wrapping call method since we are not binding methods
                    onClick={()=> this.incrementMagicNumber()}
                    // style has take double brackets since we are passing an object
                    // dash in names should be replaced by using camelCase
                    style={{width: this.state.width, height: this.state.height, fontSize: '64px'}}
                >
                    {this.state.magicNumber}
                </button>
            </div>
        );
    }
}

export default App;

Gintas Skersys

Blog by Gintas Skersys
I store my notes and project videos.