React is a JavaScript library that aims to simplify the development of visual interfaces. It does this by dividing the UI into a collection of components.
The reason React was created is because it’s easy to get lost in a bit of maze of DOM searches and updates with plain JavaScript.
ReactJS is a JavaScript library, supporting both front-end web and being run on a server, for building user interfaces and web applications. It follows the concept of reusable components
React Native is a cross-platform mobile framework that uses Reactjs for building apps and websites. React Native compiles to native app components enables the programmer to build mobile applications that can run on different platforms such as Windows, Android, iOS in JavaScript.
Install Node.js, NPM beforehand. You can follow this tutorial.
Creating React App -
npx create-react-app my-app
cd my-app
npm start
|- package.json
|- package-lock.json
|- index.js
|- index.html
Everything on screen in a React app is part of a component. Essentially, a React app is just components within components within components.
They give you a simple structure to divide every project into smaller pieces, or components. So you don’t build pages in React, you build components. At any time you just have to think about a single component rather than whole page
A React component is usually created in its own file, because that’s how we can easily reuse it (by importing it) in other components.
We call JSX everything wrapped inside the parentheses returned by the component
This looks like HTML, but it’s not really HTML. It’s a little different.
Under the hood, React will process the JSX and it will transform it into JavaScript that the browser will be able to interpret. So we’re writing JSX, but in the end there’s a translation step that makes it digestible to a JavaScript interpreter. In short, JSX is just a syntactical sugar.
click
event is fired on the button, React calls the event handler function. React supports a vast amount of types of events, like onKeyUp
, onFocus
,onChange
, onMouseDown
, onSubmit
and many more.
export default function SomeComponent() {
// ...
const handleBtnClick = (e) => {
console.log("Button was pressed");
};
return <button onClick={handleBtnClick}>Click Me</button>;
}
The state is the set of data that is managed by the component. Every React component can have its own state.
State can only be passed down the component tree (from a parent to child component). This is called unidirectional data flow, but it just means ‘one-way traffic.
Props are like parameters which we pass to our component. It can even be a function
https://cdn.sanity.io/files/oneb1r22/production/385e424dff57a487c41e3a390f8912ffacf4b7af.mp4
In a React application, data typically flows from a parent component to a child component, using props as we saw in the previous section
<WelcomeMessage myprop={"somevalue"} />
If you pass a function to the child component, you can however change the state of the parent component from a child component
function ComponentUsingCounter({}) {
//...
const [count, setCount] = useState(0);
return (
//...
<Counter setCount={setCount} />
);
}
// Counter Component
function Counter({ setCount }) {
//...
setCount(1);
//...
}
React components live certain life events that are called lifecycle events. These lifecycle’s events are tied to lifecycle methods. Like componentDidMount
, componentWillUnmount
, etc.
These methods can be divide into three categories -
props
and state
are defined. This Mounting phase only occurs once.Lifecycle Method | Description |
---|---|
componentWillMount() | is invoked immediately before mounting occurs. |
componentDidMount() | is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here. |
props
, change state
. This phase occur every-time we change our state.Lifecycle Method | Description |
---|---|
shouldComponentUpdate(object nextProps, object nextState) | is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare this.props with nextProps and this.state with nextState and return false if React should skip updating. |
componentWillUpdate(object nextProps, object nextState) | is invoked immediately before updating occurs. You cannot call this.setState() here. |
componentDidUpdate(object prevProps, object prevState) | is invoked immediately after updating occurs. |
Lifecycle method | Description |
---|---|
componentWillUnmount() | is invoked immediately before a component is unmounted and destroyed. Cleanup should go here. |
In Vanilla JS
<div>
<ul id="grocery-list">
<li>Apples</li>
<li>Oranges</li>
<li>Mangoes</li>
</ul>
<input id="item-input" />
<button id="add-button">Add Item</button>
</div>
const list = document.getElementById("grocery-list");
// Function to add item to grocery list
const addItemToList = (item) => {
const listNode = document.createElement("li");
const textNode = document.createTextNode(item);
listNode.appendChild(textNode);
list.appendChild(listNode);
};
// Items already present in grocery list
const items = ["Apples", "Mangoes", "Oranges"];
items.forEach((item) => {
addItemToList(item);
});
// To add more items
const addButton = document.getElementById("add-button");
addButton.addEventListener("click", function () {
const input = document.getElementById("item-input");
const list = document.getElementById("grocery-list");
const listNode = document.createElement("li");
const textNode = document.createTextNode(input.value);
listNode.appendChild(textNode);
list.appendChild(listNode);
});
In React
import { useState } from "react";
export default function GroceryList() {
const [items, setItems] = useState(["Apples", "Oranges", "Manges"]);
const [newItem, setNewItem] = useState("");
// runs when something is typed in input box
const handleChange = (e) => {
setNewItem(e.target.value);
};
// runs when add item button clicked
const handleClick = () => {
const updItems = [...items, newItem];
setItems(updItems);
setNewItem("");
};
return (
<div>
<h3>Grocery List</h3>
<ul id="grocery-list">
{items.map((item) => (
<li>{item}</li>
))}
</ul>
<input onChange={handleChange} />
<button onClick={handleClick}> Add Item </button>
</div>
);
}