To spend your focus time, React is a worth technology to check. I always like to learn stuff in more specific, precise, and clear ways, learning React is also not different. Here I’m sharing a React gist with all the basic terms, which will help you to get insights about React more quickly so that you will get familiar with it and take a deep dive later on if you want to play with this amazing technology.
Anyway, here is the first article on React, most probably, I will explain the concepts elaborately and separately in upcoming articles.
Prerequisites:
Before beginning to experiment with React, there are a few things you should be aware of. For instance, I would learn more about JavaScript and the DOM before attempting to learn React if I have never used them before.
Here are some things I believe are necessary for React.
- basic knowledge of HTML and CSS, JavaScript fundamentals, the DOM, and familiarity with the features and syntax of ES6.
- Also, make sure, Npm and Node.js are installed globally.
What is React
- The most popular and useful JavaScript library out there.
- React is not a framework(unlike Angular), it’s a simple library.
- React is used to build user interfaces (UI) on the front end only.
- React is a Platform-agnostic (means you can run it on any platform such as Windows, iOS, and Linux) library.
- 2011 Jordan Walke create fax js, a prototype of ReactJs. 2013 it changes from fax to ReactJs. Facebook developed the open-source technology known as React.
How does it work?
React markup syntax: JSX – JavaScript XML.
JSX used to create react element
BabelJs is used as a transpiler to convert this JSX to JS.
React – a JS object
ReactDOM – render on desktop
React Native – render in mobile
React create the HTML elements.
React DOM & Native were used for rendering this element.
All of this and more will be covered in this post, so let’s get going.
Setup & Installation.
Run the command:
npx create-react-app project-name
it will create your project with all the necessary dependency!
cd react-tutorial && npm start
it will open up a new window at localhost:3000 with your new React app.
JSX: JavaScript + XML
<h1 className="hello">My name is Clementine!</h1>
it’s not HTML, it’s JavaScript XML(JSX)
- JSX is a syntax extension to JavaScript.
- it has the full power of JavaScript.
- JSX gets compiled to
React.createElement()
, which return plain JavaScript objects called “React elements”.
JSX is actually closer to JavaScript, not HTML, so there are a few key differences to note when writing it.
className
is used instead ofclass
for adding CSS classes- Properties and methods in JSX are camelCase –
onclick
will becomeonClick
. - Self-closing tags must end in a slash – e.g.
<img />
One of the reasons people enjoy React so much is that JSX is simpler to write and comprehend than constructing and attaching multiple elements in standard JavaScript.
Rendering & conditional rendering
Rendering is nothing but showing your element on the screen.
To render a React element, first, pass the DOM element to [ReactDOM.createRoot()](<https://reactjs.org/docs/react-dom-client.html#createroot>)
, then pass the React element to root.render()
:
const root = ReactDOM.createRoot( document.getElementById('root') ); const element = <h1>Hello, world</h1>; root.render(element);
Conditional Rendering:
In React, you can create distinct components that encapsulate the behavior you need. Then, you can render only some of them, depending on the state of your application.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like [if]
or the conditional operator.
- Inline If with Logical && Operator:
true && expression
orfalse && expression
- Inline If-Else with Conditional Operator:
[condition ? true : false]
Components
Almost everything in React is made up of components, which can be either class components or simple components.
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
simple functional component
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
ES6 classes component
- Components can be divided up into separate functional units and used inside other components.
- Components can return other components, arrays, strings, and numbers.
- One important note: Component names should also always start with a capital letter (
<Wrapper/>
not<wrapper/>
)
Props & State:
One of the key features of React is how it handles data, and it achieves this by using state and properties, often known as props.
- props are inputs to a React component. It transferred data from a parent component to a child component.
- Props can’t be changed, they are readonly!
- A component needs
state
when some data associated with it changes over time.
props.number = 42; WRONG!
Use state instead, if you want to do so!
Props children:
props.children
are available on every component. It contains the content between the opening and closing tags:
<Welcome>Hello world!</Welcome>
The string Hello world! is available in props.children in the Welcome component
Important note: The most important difference between state and props is that props are passed from a parent component, but state is managed by the component itself. A component cannot change its props, but it can change its state.
Handling Events
It is fairly similar to managing events on DOM elements to handle events with React elements. There are a few syntactic variations:
- React events are named using camelCase, rather than lowercase.
- With JSX you pass a function as the event handler, rather than a string.
<button onclick="activateLasers()"> Activate Lasers </button>
HTML event
<button onClick={activateLasers}> Activate Lasers </button>
React event
List & Keys
List:
- Almost all applications need to use lists since they have some kind of repeatable content.
- By enabling the Javascript.map() technique, React significantly streamlines the rendering of lists within JSX.
const tasks = [ {text: "Buy flowers", status: "todo"}, {text: "Go to the dentist", status: "done"}, ] const tasksList = tasks.map(task => { return ( <p>{task.text} - {task.status}</p> ) });
Keys:
- When creating a list of elements, It’s a good practice to use the key, even in some cases it’s a must!
- When an element is altered, added, or removed, React can tell which element it is by using the element’s key, which functions as a form of id.
const tasks = [ {id: "1", text: "Buy flowers", status: "todo"}, {id: "3", text: "Go to the dentist", status: "done"}, ] const tasksList = tasks.map(task => { return ( <p key={task.id}>{task.text} - {task.status}</p> ) });
Forms:
Form in React works the same way as it works in HTML. It is better to use JavaScript functions instead of using the form tag on “Submit” as it redirects to another page. To achieve this functionality, we have a technique known as Controlled Components.
There are two methods offered by React for obtaining values from Form components:
- Controlled Components
- Uncontrolled Components
A controlled component is one that receives the modified value from the callback function, whereas an uncontrolled component receives it from the DOM. For instance, When the input value is changed, we may utilize the onChange function in a controlled component, and also we can get the value using DOM like ref.
<input type="text" value="Hey!" /> // Controlled <input type="text" onChange={this.handler} /> // Uncontrolled
Composition vs Inheritance
React has a powerful composition model, and they recommend using composition instead of inheritance to reuse code between components. Although React prefers the composition method, it does not state that composition is superior to inheritance. Simply put, composition suits the React component structure better.
Inheritance: When a child class derives properties from its parent class, we call it inheritance.
Composition: Instead of inheriting properties from a base class, it describes a class that can reference one or more objects of another class as instances.
Both inheritance and composition strive towards better code structures and code reuse. But React adheres to a robust component-based model, and everything in it is a component. This is one of the primary reasons that composition is a better approach than inheritance for code reuse.
Check out this short video: link
Higher-Order Components(HOCs)
- (HOC) is a sophisticated React approach for reusing component functionality.
- In more specific terms, a higher-order component is a function that accepts a component and produces a new component.
- In contrast to how a component transforms props into a user interface, a higher-order component transforms one component into another.
import React from 'react'; // Take in a component as argument InsideWrappedComponent const higherOrderwrappedComponent = (InsideWrappedComponent) => { // And return another component class HOC extends React.Component { render() { return <InsideWrappedComponent/>; } } return HOC; };
a simple structure of React HOCs
Check in-details: link
React Context
Context makes it possible to move data through the component tree without manually moving props at each level.
We used props in React applications to pass data in a top-down manner. However, in many react components it is inconvenient for certain types of props. Context provides a way to pass values between components without explicitly passing a prop through every level of the component tree.
The React context can be used in a React application in two ways:
- Set up a context provider to share the data
- Use a context consumer to receive the data
React Context API:
The React Context API is a component structure that enables data sharing between all application layers. Context API’s primary goal is to address the issue of prop drilling (also called “Threading”). The React Context API is listed below:
- React.createContext
- Context.provider
- Context.Consumer
- Class.contextType
React Hooks
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
React provides a few built-in Hooks like useState
. You can also create your own Hooks to reuse stateful behavior between different components.
Reminder:
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React function components. Don’t call Hooks from regular JS functions.
import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
a simple hook snippet
Hooks are a new addition to React 16.8. Hooks solve a wide variety of seemingly unconnected problems in React that we’ve encountered over five years of writing and maintaining tens of thousands of components.
- It’s hard to reuse stateful logic between components
- Complex components become hard to understand
- Classes confuse both people and machines
Here are the most commonly used states:
- useState: to track individual values
- useEffect: to do something after render
- useRef: to store local mutable value in a component
- useContext: to manage global data
- useReducer: when the next state depends on the previous one
- useMemo: to keep expensive, resource-intensive functions from needlessly running
- useCallback: when the child is re-rendering again and again without the need
Check in-details: link
Last Words:
This article should have given you a good introduction and all the basic terms of React.
If anything was unclear or if there is anything else you’d like to see in this article or one that follows, do let me know.