Notes for Udemy Course “The Complete React Web Developer Course (with Redux)” – https://www.udemy.com/react-2nd-edition/
React uses jsx and ES6 which means it requires Babel ( requires node ). Two scripts are required to work with React in the browser. React and ReactDOM. Below is a sample React component that has toggle visibility functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
import React from 'react'; import { render } from 'react-dom'; // required to work with React in the browser // Any component must extend React.Component and have at the very least a // render() method. class VisibilityComponent extends React.Component { // constructor for component really only needs to use super(props) instead of super() // if you need to reference the props in the constructor constructor(props) { super(props); // We bind all methods so that it references the correct this instance. this.setVisibility = this.setVisibility.bind(this); // set the initial state variables this.state = { visibility: false }; } // method that toggles the visibility state variable. setVisibility() { // updating setState should be a function that returns a new object. // if the previous state's value is needed, add prevState ( can be named anything ) // to the this.setState method's parameter. this.setState((prevState) => { return { visibility: !prevState.visibility } } ); } // return jsx that can be inclosed by ( ) render() { return ( <div> <button onClick={this.setVisibility}>Toggle visibility</button> // if statement checking visibility state value // shows 'it is shown' if true, 'not shown' if it is false. {this.state.visibility ? 'it is shown' : 'not shown'} </div> ) } } // finally, use render function from ReactDOM to attach the app to the DOM. render(<VisibilityComponent />, document.getElementById('root')); |
If components are nested, data as props can only be sent down – not up. So, on the parent component a method can be passed to the child component as a prop in order to send the information back to the parent.
Stateless functional components
Another type of component that can be reduced to a single function call because they do not have any state to handle of their own. Mostly used for “presentation” type components. They can use props but aren’t accessible through *this* .
This type of component is “faster” as it has less overhead as it doesn’t handle state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// Stateless functional component example // The name of the variable will be the component name // i.e. <User /> const User = (props) => { // like regular components, it has a render method but it is // just the body of the function itself return ( <div> Any valid JSX will work here {props.name} </div> ); }; // Can setup defaults for props using below: User.defaultProps({ name="default name if not given one" }); ReactDOM.render(<User name="Jason Rowe"/>,document.getElementById('root'); |
Small tricks for conditional rendering
|
|
// Below will only show the h2 tags if the title is not empty {this.props.title && <h2>{this.props.title}</h2>} |
For the arrow function, if you are return just an object you can use the following syntax:
|
|
this.setState(() => ({ options:[] })); // key difference is that following the arrow it must include () so // it knows it is an object rather then the normal opening and // closing brackets of the arrow function |
In React, methods to update a parent component are passed down to child components via props.
Lifecycle methods
Methods are available to hook in to when a class based component is added/removed/updated in React. Common ones to use are componentDidMount() for fetching initial data, and componentDidUpdate(prevProps, prevState) for saving updated changes back to the db.
When using componentDidUpdate, make sure the prevState and current state are not equal ( !==) so that a save to db/localStorage is not called that is not needed.
Localstorage Notes
|
|
// valid commands localStorage.setItem('name', 'Jason'); localStorage.getItem('name'); localStorage.removeItem('name'); // localStorage can only store strings. Will automatically convert // a number i.e. 26 to "26" . To make best use, we use JSON methods // below will turn a javascript object to a string that // we can store in localStorage JSON.stringify(Object); // below will turn a string back to a javascript object JSON.parse(String); |
When within a method that was attached to a onClick event ( or any other similar method ), you can reference the field/value by the following type of example:
|
|
<form onSubmit={this.handleAddOption}> <input type="text" name="option" /> <button> Add option </button> </form> // Within handleAddOption(e) can use the following to reference the // input field's value. It uses the name field for what you would reference. // in the case, name="option" e.target.elements.option.value; |
Children props ( slots )
Dynamic content that be added between a components tag can be added to be placed within the layout of the components it’s self. For example:
|
|
const Layout = (props) => return ( <div> <h1> Random Header </h1> {props.children} // above will add what was put between the <Layout> </Layout> tag </div> ); ReactDOM.render(<Layout><p> This content will be added as a child prop </p></Layout>, document.getElementById('root'); // The <p> </p> content will be added within the Layout component |
Simple form value/onChange practice:
Can create a single handleChange method to handle all form values and updates that are used in state.
|
|
handleChange = event => { //uses a object deconstructor to create name / value variables from // the even.target object const {name, value} = event.target; this.setState({ [name] : value }); } |
Now we can use same method for all form fields:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
render() { const { name, job } = this.state; return ( <form> <label>Name</label> <input type="text" name="name" value={name} onChange={this.handleChange} /> <label>Job</label> <input type="text" name="job" value={job} onChange={this.handleChange}/> </form> ); } |
Misc React Notes
In JSX, all normal html attributes such as onclick and onchange MUST be camel case.. i.e.e onClick and onChange
All components must start with a capital letter.
JSX conditional rendering :
ternary operator is accepted i.e. true ? ‘show this if true’ : ‘ value if false’
if/else can not be used in {} jsx since it is a statement and not an expression.
&& AND Operator
|
|
{user.age>18 && <p>{user.age}</p>} // If the first value is true (user.age is greater than 18) // then the second value is returned. // This is useful to only show something if a certain value is true. |