Introduction:
React is owned and maintained by Meta (formerly Facebook).
React is the one of the most demanding skillset.
Open source library for building UI.
It has rich ecosystem.
It’s a Library not a Framework.
Library centric approach.
No inherent Routing, forms, HTTP handling.
Freedom to choose the structure of the application.(Similarly, Angular has its own structure to follow.)
React itself categorized as Library in its official documentation.
Understanding the Core Differences Between React, Angular, and Vue.
Let’s jump into the fundamental concepts of react which will made the reactjs basics stronger.
Installation
Install latest and stable nodejs and code editor of your choice.
Initialize a React Application:
In this step, we create a new React application using the command
create-react-app <yourprojectname>
. This command sets up a new React project with a pre-configured build environment. It provides a boilerplate structure for the React project with minimal setup, allowing you to focus on writing code rather than configuring build tools.Navigate to projectfolder.
cd <yourprojectname>
Run npm installer.
npm i
Start the server.
npm start
Difference between npm and npx:
npm install create-react-app -g
: This will initially download the create-react-app package and then use it to generate the boilerplate code for a new React application.npx create-react-app <yourprojectname>
: This will directly generate the create-react-app boilerplate code for a new React application.Understand the folder structure here.
Let's dive into the basic concepts in React:
Components: React applications are built using components, which are reusable pieces of UI. Components can be class-based or functional, with functional components being more common in modern React development.
In React, a component can take "props" (short for properties) as input, which are used to pass data from parent components to child components. The component then uses these props to generate and return JSX (JavaScript XML), which is a syntax extension that allows you to write HTML-like code within JavaScript.
Functional Component
// src/components/Greeting.js // functional component without using arrow function. function Greeting() { return <h1>Hello World!</h1>; } // functional component using arrow function. const Greeting = () => { return <h1>Hello World!</h1> }; export default Greeting;
Class Component
This component receives props as input to the ES6 class, manages the internal state of variables, and then produces JSX as the output.
// src/components/Greeting.js import React, { Component } from "react"; class Greeting extends Component { render() { return <h1>Hello World!</h1>; } } export default Greeting;
// src/app.js import "./App.css"; function App() { return ( <div className="App"> <Greeting /> </div> ); } export default App;
JSX (JavaScript XML): JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML elements in JavaScript and place them in the DOM without using methods like
createElement()
orappendChild()
.// src/components/Greeting.js import React from "react"; // Javascript without using JSX const Greeting = () => { return React.createElement( "div", null, React.createElement("h1", null, "Hello World") ); }; // This is how it looks on using JSX. const Greeting = () => { return ( <div> <h1>Hello World</h1> </div> ); }; export default Greeting;
JSX makes code simpler and elegant.
State: State is a built-in object that stores property values that belong to a component. When the state object changes, the component re-renders to reflect the new state.
setState: This method is used to update the state object of a class component. It sets a new value to the component's state and triggers a re-render to update the UI with the new state.
import React, { Component } from "react"; class Subscribe extends Component { constructor() { super(); this.state = { message: "Welcome Visitor", }; } handleClick() { this.setState({ message: "Thanks you for subscribing", }); } render() { return ( <div> <h1>{this.state.message}</h1> <button onClick={() => this.handleClick()}>Subscribe</button> </div> ); } } export default Subscribe;
Inside the constructor, the component initializes its state. The state is an object that holds data that can change over time. Here, the state has a single property called
message
, which is initially set to "Welcome Visitor".handleClick Method
This method changes the state when called. Specifically, it updates themessage
property to "Thank you for subscribing". In React, you usethis.setState()
to update the state, which then triggers a re-render of the component to reflect the new state.Props (Properties): Props are used to pass data from one component to another. They are read-only and help make components reusable by allowing them to receive data from their parent components.
const Greeting = (props) => { return ( <div> <h1>{this.props.firstname}</h1> <h1>{this.props.lastname}</h1> </div> ); }; export default Greeting;
// src/app.js import "./App.css"; function App() { return ( <div className="App"> <Greeting firstname="Hello" lastname="World!"/> </div> ); } export default App;
Methods as Props:
import React from 'react'; // Child component function ChildComponent({ handleClick }) { return ( <button onClick={handleClick}>Click Me</button> ); } // Parent component class ParentComponent extends React.Component { handleButtonClick = () => { alert('Button clicked!'); }; render() { return ( <div> <h1>Pass Method as Parameter Example</h1> <ChildComponent handleClick={this.handleButtonClick} /> </div> ); } } export default ParentComponent;
Destructuring props and state: Destructuring is a syntax in JavaScript that allows you to extract values from arrays or properties from objects into distinct variables. In React, destructuring is commonly used to simplify the code when accessing props and state. By destructuring, you can directly extract specific properties from props or state objects, making the code cleaner and more readable. For example, instead of accessing
this.props.name
orthis.state.value
, you can destructure them asconst { name } = this.props
orconst { value } = this.state
.const Greeting = ({ firstname, lastname }) => { return ( <div> <h1>{firstname}</h1> <h1>{lastname}</h1> </div> ); }; export default Greeting;
import React, { Component } from "react"; class Greeting extends Component { constructor(props) { super(props); this.state = { firstname: "Hello", lastname: "World!", }; } render() { const { firstname, lastname } = this.state; return ( <div> <h1>{firstname}</h1> <h1>{lastname}</h1> </div> ); } } export default Greeting;
Event Handling : This will be used to handle multiple events in the ui let’s se how that woks for the click hancler.
import React, { Component } from "react"; class Counter extends Component { constructor(props) { super(props); this.state = { count: 0, }; this.incrementCount = this.incrementCount.bind(this); } incrementCount() { this.setState((prev) => ({ count: prev.count + 1, })); } decrementCount() { this.setState((prev) => ({ count: prev.count - 1, })); } incrementCountFive() { this.setState((prev) => ({ count: prev.count + 5, })); } decrementCountFive = () => { this.setState((prev) => ({ count: prev.count - 5, })); }; render() { return ( // here i have shown the 4 different ways for eventbinding <div> <h1>Count-{this.state.count}</h1> {/* Approact 1 Adding bind in constructor*/} <button onClick={this.incrementCount}>Increment</button> {/* Approach 2 */} <button onClick={this.incrementCountFive.bind(this)}> Increment 5 </button> {/* Approach 3 */} <button onClick={() => this.decrementCount()}>Decrement</button> {/* Approach 4 */} <button onClick={this.decrementCountFive}>Decrement 5</button> </div> ); } } export default Counter;
Conditional Rendering: This technique allows you to render different UI elements or components based on certain conditions. In React, you can achieve conditional rendering using
if-else
statements or the ternary operator. This approach helps in displaying content dynamically based on the application's state or props. For example, you might show the username as "guest" until they log in.import React, { Component } from "react"; class ConditionalRendering extends Component { constructor(props) { super(props); this.state = { userLoggedIn: false, }; } render() { // Method 1 if (!this.state.userLoggedIn) { return ( <div> <h1>Hello Guest</h1> </div> ); } else { return ( <div> <h1>Hello Sahana</h1> </div> ); } }
// Method 2 return this.state.userLoggedIn ? ( <div> <h1>Hello Sahana</h1> </div> ) : ( <div> <h1>Hello Guest</h1> </div> );
// Method 3 return ( <div> <h1>Hello {this.state.userLoggedIn ? "Sahana" : "Guest"}</h1> </div> );
Lists in React: Lists are used to store multiple elements and work with them. They allow you to render a collection of items dynamically by iterating over the list and creating a component for each item. This is commonly done using the
map()
function, which transforms each element in the list into a React component. Lists are essential for displaying data sets, such as arrays of objects, in a structured and efficient manner.import React from "react"; function NameList() { const names = [ { id: 1, name: "alex", age: 22 }, { id: 2, name: "adam", age: 18 }, { id: 3, name: "john", age: 17 }, { id: 4, name: "jack", age: 12 }, ]; const nameList = names.map((item, index) => ( // key should be unique <div key={item.id}> <h1> {item.id} {item.name} {item.age} </h1> </div> )); return <div>{nameList}</div>; } export default NameList;
Styling and CSS Basics: In React, there are four different ways to style components:
CSS Stylesheets: Traditional CSS files where styles are defined and then applied to elements using class names.
.primary { color: orange; } .font-xl { font-size: 72px; }
import React from 'react' import './myStyles.css' function Stylesheet (props) { let className = props.primary ? 'primary' : ''; return ( <div> <h1 className={${className} font-xl }>Stylesheets</h1> </div> ) } export default Stylesheet
Inline Styling: Styles are applied directly to elements using the
style
attribute, which accepts a JavaScript object with camelCased properties.import React from 'react' const heading = { fontSize: '72px', color: 'blue' } function Inline() { return ( <div> <h1 style={heading}>Inline</h1> </div> } export default Inline
CSS Modules: A CSS file in which all class and animation names are scoped locally by default, allowing for modular and reusable styles.
/* /src/appStyles.module.css */ .success{ color:green; }
import styles from './appStyles.module.css' function Greet() { return <h1 className={styles.success}>Hello Sahana</h1>; }
CSS-in-JS Libraries: Libraries like styled-components or emotion that allow you to write CSS directly within JavaScript, providing dynamic styling capabilities. This method has its own series of concepts to learn.
Basics of Form Handling : The below
form
component demonstrates how to handle forms in React. Here's an explanation of how it works:State Initialization: The component's state is initialized in the constructor with three properties:
username
,comments
, andfruitSelect
. These properties will hold the values of the form inputs.Event Handlers:
handleChangeUserName
: Updates theusername
state when the user types in the text input.handleChangeComments
: Updates thecomments
state when the user types in the textarea.handleChangefruitSelect
: Updates thefruitSelect
state when the user selects an option from the dropdown.
Form Submission: The
handleSubmit
method is called when the form is submitted. It prevents the default form submission behavior usingevent.preventDefault()
and displays an alert with the current values ofusername
,comments
, andfruitSelect
.Render Method: The
render
method returns the JSX that defines the form's UI. It includes:A text input for the username, with its value controlled by the
username
state and updated viahandleChangeUserName
.A textarea for comments, with its value controlled by the
comments
state and updated viahandleChangeComments
.A select dropdown for choosing a fruit, with its value controlled by the
fruitSelect
state and updated viahandleChangefruitSelect
.A submit button that triggers the
handleSubmit
method when clicked.
Destructuring State: The state properties are destructured in the
render
method for cleaner access tousername
,comments
, andfruitSelect
.
This component demonstrates how to create controlled form elements in React, where the form inputs are tied to the component's state, allowing for dynamic and interactive form handling.
import React, { Component } from "react";
class Form extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
comments: "",
fruitSelect: "",
};
}
handleChangeUserName = (event) => {
this.setState({ username: event.target.value });
};
handleChangeComments = (event) => {
this.setState({ comments: event.target.value });
};
handleChangefruitSelect = (event) => {
this.setState({ fruitSelect: event.target.value });
};
handleSubmit = (event) => {
event.preventDefault();
alert(
`Username ${this.state.username}, Comments ${this.state.comments}, Selected Value : ${this.state.fruitSelect}`
);
};
render() {
const { username, comments, fruitSelect } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>User Name</label>
<input
type="text"
value={username}
onChange={this.handleChangeUserName}
/>
</div>
<div>
<label>Comments</label>
<textarea
value={comments}
onChange={this.handleChangeComments}></textarea>
</div>
<div>
<label>Select Value</label>
<select
value={fruitSelect}
onChange={this.handleChangefruitSelect}>
<option value="">Select</option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Grapes">Grapes</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
);
}
}
export default Form;
Life Cycle Methods: In React, lifecycle methods are special methods that are invoked at different stages of a component's existence. They allow you to run code at specific points in a component's lifecycle, such as when it is created, updated, or destroyed.
Mounting: This phase occurs when a component is being inserted into the DOM.
constructor()
: Initializes the component's state and binds event handlers.componentDidMount()
: Invoked immediately after a component is mounted. It's a good place to initiate network requests or set up subscriptions.
Updating: This phase happens when a component's state or props change.
static getDerivedStateFromProps():
This method is invoked right before rendering and is used to update the state based on changes in props.shouldComponentUpdate():
This method determines whether the component should re-render in response to changes in props or state, allowing for performance optimizations.render():
This method is required in every class component and returns the JSX that represents the component's UI.getSnapshotBeforeUpdate():
This method is called right before the DOM is updated, allowing you to capture information (e.g., scroll position) from the DOM before it changes.componentDidUpdate(prevProps, prevState)
: Called immediately after updating occurs. You can use it to perform operations based on the previous state or props.
Unmounting: This phase occurs when a component is being removed from the DOM.
componentWillUnmount()
: Invoked immediately before a component is unmounted and destroyed. It's used to clean up resources like timers or network requests.
Error Handling: This phase is used to catch errors in the component tree.
The
static getDerivedStateFromError()
function is a lifecycle method used to update the state of a component in response to an error thrown in a descendant component, allowing you to render a fallback UI.componentDidCatch(error, info)
: Invoked when an error is thrown in a child component. It allows you to handle errors gracefully.
import React, { Component } from "react";
import LifeCycleB from "./LifeCycleB";
class LifeCycleA extends Component {
constructor(props) {
super(props);
this.state = {
name: "Hello",
};
console.log("Life CycleA Constructor");
}
changeState() {
this.setState({
name: "World!",
});
}
static getDerivedStateFromProps(props, state) {
console.log("Life CycleA getDerivedStateFromProps");
return null;
}
shouldComponentUpdate() {
console.log("Life CycleA shouldComponentUpdate");
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("Life CycleA getSnapshotBeforeUpdate");
return null;
}
componentDidUpdate() {
console.log("Life CycleA componentDidUpdate");
}
componentDidMount() {
console.log("Life CycleA componentDidMount");
}
render() {
console.log("Life CycleA render");
return (
<div>
<h1>{this.state.name}</h1>
<button onClick={() => this.changeState()}>Change State</button>
</div>
);
}
}
export default LifeCycleA;
//Output for Mounting:
Life CycleA Constructor
Life CycleA getDerivedStateFromProps
Life CycleA render
LifeCycleB Constructor
LifeCycleB getDerivedStateFromProps
LifeCycleB render
Life CycleB componentDidMount
Life CycleA componentDidMount
// Output for Updating:
Life CycleA getDerivedStateFromProps
Life CycleA shouldComponentUpdate
Life CycleA render
LifeCycleB getDerivedStateFromProps
Life CycleB shouldComponentUpdate
LifeCycleB render
Life CycleB getSnapshotBeforeUpdate
Life CycleA getSnapshotBeforeUpdate
Life CycleB componentDidUpdate
Life CycleA componentDidUpdate
These are the basics of React which one should know. Thank for reading till the end.
As a beginner, this is a great opportunity to join the developer community, where I can expect people to appreciate me when I do a good job and provide feedback to help me learn.
This is my first blog, and I encourage all of you to share your feedback. It will motivate me to do more.