Install sass
npm install node-sass
$myRed: red; h1 { color: $myRed; }
import React from 'react'; import ReactDOM from 'react-dom'; import './mysass.scss'; class Profile extends React.Component { render() { return ( <div> <h1>Hello World!</h1> </div> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Inline Styling
To style an element with the inline style attribute, the value must be a JavaScript object
class Profile extends React.Component { render() { return ( <div> <h1 style={{color: "red"}}>Hello World!</h1> </div> ); } }
In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects also use curly braces, the styling in the example above is written inside two sets of curly braces {{}}
camelCased Property Names
Since the inline CSS is written in a JavaScript object, properties with two names, like background-color
, must be written with camel case syntax:
class Profile extends React.Component { render() { return ( <div> <h1 style={{backgroundColor: "lightblue"}}>Hello World!</h1> </div> ); } }
Javascript Object
You can also create an object with styling information, and refer to it in the style attribute.
class Profile extends React.Component { render() { const mystyle = { color: "white", backgroundColor: "blue", padding: "10px", fontFamily: "Arial" }; return ( <div> <h1 style={mystyle}>Hello World!</h1> </div> ); } }
CSS Stylesheet
You can write your CSS styling in a separate file, just save the file with the .css file extension, and import it in your application.
import React from 'react'; import ReactDOM from 'react-dom'; import './App.css'; class Profile extends React.Component { render() { return ( <div> <h1>Hello World!</h1> </div> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
CSS Module
Another way of adding styles to your application is to use CSS Modules. CSS Modules are convenient for components that are placed in separate files.
.myBlue { color: blue; padding: 40px; font-family: Arial; text-align: center; }
import React from 'react'; import ReactDOM from 'react-dom'; import styles from './mystyle.module.css'; class Profile extends React.Component { render() { return <h1 className={styles.myblue}>Hello World!</h1>; } } export default Profile;
Handling forms is about how you handle the data when it changes value or gets submitted.
In HTML, form data is usually handled by the DOM.
In React, form data is usually handled by the components.
When the data is handled by the components, all the data is stored in the component state
.
You can control changes by adding event handlers in the onChange
attribute:
import React from 'react'; class Form extends React.Component { constructor(props) { super(props); this.state = { firstName: 'Folau' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({firstName: e.target.value}); } render() { return ( <div> <input type = "text" value = {this.state.firstName} onChange = {this.updateState} /> <h4>{this.state.firstName}</h4> </div> ); } } export default Form;
You must initialize the state in the constructor method before you can use it.
You get access to the field value by using the event.target.value syntax.
Submitting Form
You can control the submit action by adding an event handler in the onSubmit attribute.
import React from 'react'; import ReactDOM from 'react-dom'; class Form extends React.Component { constructor(props) { super(props); this.state = { username: '', age: null, }; } mySubmitHandler = (event) => { event.preventDefault(); alert("You are submitting " + this.state.username); } myChangeHandler = (event) => { let nam = event.target.name; let val = event.target.value; this.setState({[nam]: val}); } render() { return ( <form onSubmit={this.mySubmitHandler}> <h1>Hello {this.state.username} {this.state.age}</h1> <p>Enter your name:</p> <input type='text' name='username' onChange={this.myChangeHandler} /> <p>Enter your age:</p> <input type='text' name='age' onChange={this.myChangeHandler} /> <input type='submit' /> </form> ); } } ReactDOM.render(<Form />, document.getElementById('root'));
Note that we use event.preventDefault() to prevent the form from actually being submitted.
It’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called “controlled components”.
Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc.
A good practice is to put the event handler as a method in the component class:
class Profile extends React.Component { changeName() { alert("name changed!"); } render() { return ( <button onClick={this.changeName}>change your name!</button> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Bind this
For methods in React, the this
keyword should represent the component that owns the method. That is why you should use arrow functions. With arrow functions, this
will always represent the object that defined the arrow function.
class Profile extends React.Component { changeName = () => { alert(this); /* The 'this' keyword refers to the component object */ } render() { return ( <button onClick={this.changeName}>change your name!</button> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Why use arrow function?
In class components, the this
keyword is not defined by default, so with regular functions the this
keyword represents the object that called the method, which can be the global window object, a HTML button, or whatever.
Read more about binding this
in our React ES6 ‘What About this?’ chapter.
If you must use regular functions instead of arrow functions you have to bind this
to the component instance using the bind()
method:
Passing parameters
If you want to send parameters into an event handler, you have two options:
Make an anonymous arrow function
class Profile extends React.Component { changeName = (a) => { alert(a); } render() { return ( <button onClick={() => this.changeName("Goal")}>Change your name!</button> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Bind the event handler to this. Note that the first argument has to be this.
class Profile extends React.Component { changeName(a) { alert(a); } render() { return ( <button onClick={this.changeName.bind(this, "Lau")}>change your name!</button> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Note: If you send arguments without using the bind
method, (this.shoot(this, "Goal")
instead of this.shoot.bind(this, "Goal")
), the shoot
function will be executed when the page is loaded instead of waiting for the button to be clicked.
It is generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
Remember that props are evaluated before they’re passed down. When written without the arrow function, a link or button would be called when ui renders, instead of when the link is clicked. That’s not what we want. Wrapping it in an arrow function delays execution until the user clicks the link.
Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: Mounting, Updating, and Unmounting.
Mounting
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The render()
method is required and will always be called, the others are optional and will be called if you define them.
Constructor
The constructor()
method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state
and other initial values.
The constructor()
method is called with the props
, as arguments, and you should always start by calling the super(props)
before anything else, this will initiate the parent’s constructor method and allows the component to inherit methods from its parent (React.Component
).
class Profile extends React.Component { constructor(props) { super(props); this.state = {name: "Folau"}; } render() { return ( <h1>My name is {this.state.name}</h1> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
The getDerivedStateFromProps()
method is called right before rendering the element(s) in the DOM. This is the natural place to set the state
object based on the initial props
. It takes state
as an argument, and returns an object with changes to the state
.
class Profile extends React.Component { constructor(props) { super(props); this.state = {name: ""}; } static getDerivedStateFromProps(props, state) { return {name: props.name }; } render() { return ( <h1>My name is {this.state.name}</h1> ); } } ReactDOM.render(<Profile name="Folau"/>, document.getElementById('root'));
render()
The render()
method is required, and is the method that actually outputs the HTML to the DOM.
The componentDidMount()
method is called after the component is rendered.
This is where you run statements that requires that the component is already placed in the DOM.
class Profile extends React.Component { constructor(props) { super(props); this.state = {name: "Folau"}; } componentDidMount() { setTimeout(() => { this.setState({name: "Lisa"}) }, 1000) } render() { return ( <h1>My name is {this.state.name}</h1> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Updating
The next phase in the lifecycle is when a component is updated.
A component is updated whenever there is a change in the component’s state
or props
.
React has five built-in methods that gets called, in this order, when a component is updated:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The render()
method is required and will always be called, the others are optional and will be called if you define them.