React components has a built-in state
object. The state
object is where you store property values that belongs to the component. When the state
object changes, the component re-renders. State is similar to props, but it is private and fully controlled by the component.
class Profile extends React.Component { constructor(props) { super(props); this.state = { name: "Folau" }; } render() { return ( <div> <h1>My name is {this.state.name}</h1> </div> ); } }
Change state
To change a value in the state object, use the this.setState()
method. When a value in the state
object changes, the component will re-render, meaning that the output will change according to the new value(s).
class Profile extends React.Component { constructor(props) { super(props); this.state = { name: "Folau" }; } changeName = () => { this.setState({name: "Lisa"}); } render() { return ( <div> <h1>My name is {this.state.brand}</h1> <button type="button" onClick={this.changeName} >Change Name</button> </div> ); } }
Always use the setState()
method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).
Don’t change state directly
this.state.comment = 'Hello';
Props are like function arguments, and you send them into the component as attributes. Props are passed to components via HTML attributes. React Props are like function arguments in JavaScript and attributes in HTML Passing props is how information flows in React apps, from parents to children.
To send props into a component, use the same syntax as HTML attributes:
const homeElement = <Home name="Folau" />; class Home extends React.Component { render() { return <h2>Hi, my name is {this.props.name}!</h2>; } }
Pass data
class Home extends React.Component { render() { return <h2>I am a {this.props.userInfo.name}!</h2>; } } class Profile extends React.Component { render() { const userInfo = {name: "Folau"}; return ( <div> <Home userInfo={carinfo} /> </div> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Props can accept all sorts of things: Numbers, Booleans, Strings, Objects, even Functions. Early on you might start to wonder, should you pass an object and let the component extract what it needs? Or should you pass the specific pieces of data that the component requires?
You won’t use all of an object attributes in most cases.
It’s a good idea to keep the knowledge of data structures contained to as few places as possible to reduce the cost of change.
If your component has a constructor function, the props should always be passed to the constructor and also to the React.Component via the super()
method.
React Props are read-only! You will get an error if you try to change their value.
If you can’t change props, but you need to communicate something up to a parent component, how does that work?
If a child needs to send data to its parent, the parent can inject a function as a prop, like this:
function handleAction(event) { console.log('Child did:', event); } function Parent() { return ( <Child onAction={handleAction}/> ); } function Child({ onAction }) { return ( <button onClick={onAction}/> ); }
The Child component receives a prop named onAction, which it can call whenever it needs to send up data or notify the parent of an event. You’ll notice that the built-in button element accepts an onClick prop, which it’ll call when the button is clicked.
React renders HTML using ReactDOM.render().
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
import React from 'react'; class App extends React.Component { render() { return ( <div> <Header/> <Content/> </div> ); } } class Header extends React.Component { render() { return ( <div> <h1>Header</h1> </div> ); } } class Content extends React.Component { render() { return ( <div> <h2>Content</h2> <p>The content text!!!</p> </div> ); } } export default App;
Root document
The root node is the HTML element where you want to display the result.
ReactDOM.render( <Providerstore={createStore(allReducers, applyMiddleware(thunk))}> <React.StrictMode> <Router> <Routepath="/"exactcomponent={Home}/> </Router> </React.StrictMode> </Provider>, document.getElementById('root') );
<body> <header id="root"></header> </body>
function UserWelcome(props) { return <h1>Welcome back!</h1>; } function GuestWelcome(props) { return <h1>Please sign up.</h1>; }
class Content extends React.Component { render() { if (this.state.isLoggedIn) { return <UserWelcome />; } return <GuestWelcome />; } } export default App;
It’s generally a bad idea to create new functions to pass into props in the render function.
The reason it’s bad to create new functions is for performance: not because functions are expensive to create, but because passing a new function down to a pure component every time it renders means that it will always see “new” props, and therefore always re-render (needlessly).
Avoid creating a new function in render when:
Function components and classes that extend Component are not pure. They will always re-render, even if their props haven’t changed. If a class extends PureComponent instead, though, it is pure and it will skip re-rendering when its props are unchanged. Avoiding needless re-renders is the easiest way to improve performance in a React app.
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()
and/or appendChild()
methods.
JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications. JSX is a syntax extension to JavaScript. It may remind you of a template language, but it comes with the full power of JavaScript.
React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages. React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
Expression in JSX
With JSX you can write expressions inside curly braces { }
. The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result.
const element = <h1>React is {5 + 5} times better with JSX</h1>;
Inserting a big block of HTML code
const listOfNames = (
<ul>
<li>John</li>
<li>Peter</li>
<li>Charlie</li>
</ul>
);
One top element
The HTML code must be wrapped in ONE top level element. So if you like to write two headers, you must put them inside a parent element, like a div
element
const listOfNames = (
<div>
<h1>John</h1>
<h1>Peter</h1>
</div>
);
Elements must be closed
JSX follows XML rules, and therefore HTML elements must be properly closed. Close empty elements with />
const myelement = <input type="text" />;
Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.
const profileImg = <img src={user.imgUrl}></img>;
If a tag is empty, you may close it immediately with />
, like XML:
const profileImg = <img src={user.imgUrl}/>;
JSX tags may contain children:
const message = ( <div> <h1>Hi there!</h1> <h2>Come have lunch with me.</h2> </div> );
Note that everything is converted to a string before being rendered.
React uses ES6’s features such as class, arrow functions, variables(let, var, const), for..in, for..of, and others.
Classes
class User { constructor(name) { this.name = name; } present() { return 'Hi my name is ' + this.name; } } class Employee extends User { constructor(name, age) { super(name); this.age = age; } show() { return this.present() + ', I am ' + this.age + ' years old'; } } Jimmy = new Employee("Jimmy", 25);
A class can have attributes, methods, and state. You can extend a class and add functionality.
Arrow functions
Regular JS
sayHi = function(name) { return "Hi! my name is " + name; }
ES6 arrow function
sayHi = (name) => { return "Hi! my name is " + name; }
Default functions
In ES6, a function allows the parameters to be initialized with default values if no values are passed to it or it is undefined.
function add(a, b = 1) { return a+b; } console.log(add(4)) 5 console.log(add(4,2)) 6
Rest Parameters
You can pass in as many parameters to a method but the values passed must all be of the same type.
function fun1(...params) { console.log(params.length); } fun1(); 0 fun1(5); 1 fun1(5, 6, 7); 3
Variables
There are three ways to defined variables with ES6:
a. var(outside of a function) is used as a global variable.
b. var(inside of a function) only belongs to that function.
c. var(inside of a block, like if-statement or for-loop) is still available outside of the block.
d. let is block or function scope.
e. const is used to create variables that don’t change once initialized.
For in
for…in loop is used to loop through an object’s properties
for (variablename in object) {
statement or block to execute
}
var user = {name:"John", age:2, id:1}; for (var attribute in user) { console.log(user[attribute]); } // print out int the order they are organized. John 2 1
For of
for…of loop is used to iterate iterables like array and map.
let names = ['Folau', 'Lisa', 'Kinga', 'Fusi']; for (let name of names) { console.log(name); } Folau Lisa Kinga FusiAugust 6, 2019