React is a popular JavaScript library. As a beginner, you may have a question about what can we build with React. So React is a declarative, efficient, and flexible JavaScript library used to build user interface means (UI) of web applications.
React is not a framework, There are many books and debates where some people say that React is a framework. The framework is a complete solution. Everything you need to make your application is built-in. A framework usually wants you to code everything a certain way
In this blog, we will go through some basic React fundamentals topics that are important for those who want to start ReactJs.
JSX IN REACTJs
JSX is like a combination of JavaScript and HTML syntax, And you can use both language syntax in the same file with the help of the JSX extension.
Example-
Mix HTML in JavaScript
What are you thinking, I will not mix both languages like vegetables, Just following the rules of the JavaScript syntax.
const element = <h1>Hello, JSX!</h1>;
With JSX, you can embed HTML-like code directly within your JavaScript code. For example, instead of creating elements using React.createElement()
you can use JSX syntax.
JavaScript Expressions
You can also embed JavaScript expressions within JSX by wrapping them in curly braces {}
This allows you to dynamically compute values and include them in your JSX code
const name = "Mohit";
const element = <h1> Get Out, {name}</h1>;
JSX Elements
JSX elements resemble HTML elements, but they are actually plain JavaScript objects representing React components. These components can be user-defined or built-in ones like `div`, `span`, etc.
const element = <div className="Class"> This is JSX Element.</div>
Attributes and Props
JSX also supports HTML attributes and properties in a way similar to HTML. You can pass data components using attributes
const Button = (props) => <button onClick={props.onClick}>{props.label}</button>;
Conditional Rendering
JSX allows you to conditionally render content using JavaScript expressions. You can use ternary operators or `if` statements within JSX.
const isLoggedIn = true;
const element = (
<div>
{isLoggedIn ? <p> Welcome, user! </p> : <p>Please log in.</p>}
</div>
);
Mapping and iterating
You can also use JavaScript's `map` function, and you must have already read about the map function, If you have not read then read my array methods article.
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => <li key={number}>{number}</li>);
const element = <ul>{listItems}</ul>;
Components Composition
JSX allows you to compose components by embedding them within each other
const App = () => (
<div>
<Header />
<Content />
<Footer />
</div>
);
Congratulations You have learned all about the JSX.
Component In React
In React, we describe UI using components that are reusable, composable, and stateful. We can compare components with a simple function. We can call a function with some input, and it returns some output. We can reuse functions when we need them and compose bigger functions from smaller ones. React components are the same. Their output is a set of props, and their output is a description of a UI. We can reuse a single component in multiple UI, and components can contain other components.
There are two types of components in React
Functional Components
These are also known as "stateless components" or "functional stateless components." They are defined using JavaScript functions and take in props (properties) as arguments, returning JSX to describe what should be rendered.
const Greeting = (props) => { return <p> hello, {props.name}</p>; };
Class Components
These are also known as "stateful components" or simply "class components." They are defined using JavaScript classes and extend React's
Component
class. Class components have the ability to manage internal state, making them useful for more complex logic and interactions.const Greeting = (props) => { return <p> hello, {props.name}</p>; }; class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Increment </button> </div> ); } }
Components can be used and resued throughout your application's UI. They can also be composed together, allowing you to build complex interfaces from smaller reusable parts.
Example-
const App = () => {
return (
<div>
<Greeting name="Mohit" />
<Greeting name="Sohail" />
<Counter />
</div>
);
};
In the context of React and JSX, a component is a reusable building block that encapsulates a specific piece of functionality or user interface. Components allow you to break down your user interface into smaller, manageable pieces, making it easier to develop, test, and maintain your application.
There are two main types of components in React:
Functional Components: These are also known as "stateless components" or "functional stateless components." They are defined using JavaScript functions and take in props (properties) as arguments, returning JSX to describe what should be rendered.
const Greeting = (props) => { return <p>Hello, {props.name}!</p>; };
Class Components: These are also known as "stateful components" or simply "class components." They are defined using JavaScript classes and extend React's
Component
class. Class components have the ability to manage internal state, making them useful for more complex logic and interactions.class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Increment </button> </div> ); } }
Components can be used and reused throughout your application's UI. They can also be composed together, allowing you to build complex interfaces from smaller, reusable parts. For example:
const App = () => {
return (
<div>
<Greeting name="Sohail" />
<Greeting name="Mohit" />
<Counter />
</div>
);
};
In this example, the Greeting
component is reused with different names and the Counter
component is included within the App
component.
Virtual DOM in ReactJs
The Virtual DOM (VDOM) is a concept used by libraries like React to optimize the process of updating the user interface in web applications. It's an abstract representation of the actual browser DOM (Document Object Model). The idea behind the Virtual DOM is to provide a more efficient way to update the UI by minimizing direct manipulation of the real DOM, which can be slow and resource-intensive.
HOOKS in ReactJs
Hooks are a feature introduced in React 16.8 that allows you to use state and other React features in functional components, rather than being limited to class components. Hooks provide a more concise and organized way to manage component state, lifecycle, and other behaviors, without the need to write class-based components.
There are two hooks that are most common in React.
useState()
The
useState
hook allows functional components to manage the local state.It returns a state variable and a function to update that variable.
Example-
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
useEffect()
useEffect()
The
useEffect
hook is used for side effects and handling component lifecycle.It replaces lifecycle methods like
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
.Example-
import React, { useState, useEffect } from 'react'; function DataFetching() { const [data, setData] = useState([]); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }
These are just a Two examples of hooks in React. Hooks enable you to organize your component logic in a more modular and functional manner, making it easier to reuse and test your code. They have become an integral part of modern React development.
Props and State
In React, both "props" and "state" are important concepts that deal with data management within components, but they serve different purposes and are used in different scenarios.
Props (Properties)
Props, short for "properties," are a way to pass data from a parent component to a child component. They are used to make components more dynamic and configurable, allowing you to customize the behavior and appearance of a component based on the data you pass to it. Props are read-only and cannot be modified within the component that receives them.
Key points about props:
Passing Data: Props are passed down from a parent component to a child component through attributes in JSX.
Immutable: Props are immutable, meaning they cannot be changed or modified by the child component.
Configuration: Props are used to configure and customize the behavior of components.
Functional and Class Components: Props can be used in both functional and class components.
Example-
// Parent component
const App = () => {
return <Greeting name="Alice" />;
};
// Child component
const Greeting = (props) => {
return <p>Hello, {props.name}!</p>;
};
State
state represents the internal data of a component that can change over time. It allows components to keep track of dynamic information and re-render based on updates to that data. State is typically used in class components but can also be used in functional components using the useState
hook. Unlike props, state can be modified by the component itself using a special function provided by React.
Key points about state:
Component-Specific Data: State is internal to a component and holds data that can change during the component's lifecycle.
Mutable: State can be updated using the
setState
function (in class components) or the state updater function (in functional components).Reactive Updates: When state changes, React will automatically re-render the component to reflect the updated data.
Class Components and Hooks: State can be used in class components with the
this.state
mechanism or in functional components using theuseState
hook.Example:
// Class component
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
Props are used for passing data from parent to child components to configure their behavior, while state is used for managing internal dynamic data within a component and causing re-renders when that data changes. Both props and state play essential roles in building dynamic and interactive user interfaces in React applications.
That was the today basic and if you want to read more in-depth then you can go to React blog official website thank you for reading this article See you on another blog. #kohi9noor