Learning React Tutorial Notes

Personal notes from the React tutorial to reinforce learning :)

A great, quick way to initialize projects is to use

npx create-react-app name-of-app

This fills out a basic package.json and setups the project structure and hooking up a webpack based build pipeline. The project can then be built and previewed with the command:

npm start

The tutorial is written in JSX which is one of those hybrid js/es6 based languages that can include HTML mark up, making everything much easier. So far React looks very nice and java-y. I think it is using es6 modules as there are a bunch of

import xxx from

 at the top.

Components are wrapped up as objects that extend

React.Component

If you specify a constructor you must call super to pass the properties to the base class.

Class MyObject extends React.Component{
    constructor(props){
        super(props);
        //do your own initialisation.
    }
}

When extending React.Component you implement/extend (not sure yet may need to check) render. This returns a React Element. This is a little like angular views where you have html with js inside curly braces.

Properties are passed to a components constructor via an object literal. A function can easily be referenced from there and declared in the parent. In this example, we have made OtherComponent into a controlled component. The onClick event of the rendered component calls a function reference where the function is declared in the component MyObject, allowing it access variables in MyObject, OtherComponents parent component.

function OtherComponent(props){
    return(<button className="loveHate" onClick={props.onClick}>
        {props.property1}
        </button>);
    }
}

class MyObject extends React.Component{
    
    constructor(props){
        super(props);
        this.state = {
            myValue : 'love',
        }
    }

    handleClick(val){
        this.setState({
            myValue : this.state.myValue == 'love' ? 'hate' : 'love';,
        });
    }

    doSomthingTricky(val){
        return <OtherComponent
            property1={this.state.myValue}
            onClick={() => this.state.handleClick()}
        />
    }

    render(){
        return(
            <div>{doSomthingTricky()}</div>
        );
    }
}

Passing functions as properties avoid communication from child to parent try to keep it parent tells child. In the function handleClick you can see that we don't update the property but instead replace it with a new object so as to maintain immutability. With everything being immutable we have a pure component.