Published On: July 24th, 202316.6 min read

This is a beginner-friendly walkthrough for setting up a React application and creating reusable components, covering key concepts such as state management, event handling, and passing data via props. It serves as a practical introduction to building dynamic and interactive user interfaces using React.

React JS  18

 

Prerequisite–

  • HTML 
  • CSS
  • JS

Why we will use typescript 

  • faster development
  • finding bugs in earlier development

React is a JS library for creating dynamic & interactive user interfaces. It was built by Meta in 2013. It’s the most widely used JavaScript library for frontend development.

Why is it created?

Well html work as Dom which is a tree of the component. For doing actionable work we need to write a lot of JavaScript code. So now in React we think of every component as a reusable component.

Components help us write reusable modular and better-organized code.

Let’s start setting up React:

  • For the environment please make sure your node version is above 16.x.x & stable.
    • On Linux run the command: “node -v” for checking the version.
  • Choose your favorite ide like vs code.
    • Then install an extension like Prettier.
      • goto settings of vs code then search for “format on save”
      • Mark tick for format on save this will save time.

Creating A react App:

Two ways to create React app

1) Create React App (CRA) – an official tool by meta for creating React app.

2)Vite – benefits of Vite are it creates react faster & gives us a small bundle tool. we go for the simplest way.

Follow the steps: 

  1. In Terminal type “npm create vite@4.1.0” for having exact same experience as this blog or “npm create vite@latest” for the latest one.
    •  Type Y.
    • Change the name as you want or type “react-app”.
    • Select React.
    • Select Typescript for this blog.
  2.  “cd react-app” (here “react-app” is the project name).
  3.  “npm install” (for installing third-party library)
  4. “code .” (for the opening project in vs code).
  5. Run “npm run dev” to launch the web server on localhost:xxxx. open the link you will see your project is up & running.

Project structure:

  • node_modules: This is where all the third-party libraries are installed there.
  • public: here public assets like website images are stored.
  • src: here it will contain the source code of our application.
  • Then we have index.html, which contains very basic HTML code. there we have a div with an id of the root which is a container of our app. After that, we script tag this as the entry point of our application.
  •  Then we have package.json where we can find information about our project like name, version, dependencies, dev-dependencies, etc.
  •  Then we have tsconfig.json file which has a bunch of setting to tell the compiler how to compile our code javascript.
  •  Then we have vite.config.ts like the previous file its also a configuration file for vite

Creating React Component:

  1. To create React Component create a file name “Message.tsx” under “src” directory.
  2. There are two ways to create a React component  
    • Using Javascript Class (we will go this way because this is easier and more precise & its recommended approach for new projects)
    • Or using Javascript Function

    **If you observe function naming this convention is called PascalCasing. It means we should capitalize every first letter of the word. We have to follow this convention because react developer & other developers expect this naming convention. **

“`

Add this code in Message.tsx file

function Message() {
 return <h1>Hello World</h1>;
}
export default Message;

Then add this code to App.tsx 

import Message from "./Message";
function App() 
{
 return (
   <div>
     <Message />
   </div>
 );
}
export default App;

“`

This will result in Hello World in our project.

** The syntax is used here is called JSX: JavaScript XML. This code is compiled down to JavaScript. ** 

Let’s know How React Works:

React is a JavaScript library that helps you build user interfaces. It does this by creating a virtual DOM, which is a lightweight representation of the actual DOM. When the state of the application changes, React compares the virtual DOM to the actual DOM and only updates the parts of the DOM that have changed. This makes React very efficient, as it only needs to update the parts of the UI that have changed, rather than the entire UI.

Creating a ListGroup Component:

  1. First, we will install Bootstrap to give our application a modern look.
    Run this command ”npm i bootstrap@5.2.3”
  2. In ‘src’ directory there is a file name ‘App.css’, we have deleted all generated code by vite.
  3. Again in ‘src’ directory delete ‘index.css’ file completely.
  4. In ‘scr’, open file ‘main.tsx’ and replace the line “ import ‘./index.css’ ”, with  “ import ‘bootstrap/dist/css/bootstrap.css’ ”. If we go browser we see changes in our site. Now Hello World is aligned top left.
  5. Now create a folder named ‘components’ under ‘src’ directory.(It’s not mandatory but by convention, we put all of our components in this folder).
  6. Now create a file named ‘ListGroup.tsx’ under the ’components’ folder. ( look again we are following PascalCasing convention )

“`
Add this code snippet into ‘ListGroup.tsx’ file.

function ListGroup() {
 return (
   <ul className="list-group">
     <li className="list-group-item">An item</li>
     <li className="list-group-item">A second item</li>
     <li className="list-group-item">A third item</li>
     <li className="list-group-item">A fourth item</li>
     <li className="list-group-item">And a fifth one</li>
   </ul>
 );
}
export default ListGroup;

Then add following code snippet in ‘App.tsx’ file

import ListGroup from "./components/ListGroup";
function App() {
 return (
   <div>
     <ListGroup />
   </div>
 );
}
export default App;

“`

Now check the site in browser. So this kind of boring it does add functionality to site right? So in the next part, we will make it render dynamically.

Fragment:

If we add an element like “<h1></h1>” in ‘ListGroup.tsx’ react will give a bunch of errors because in react a component cannot return more than one element. So for avoiding this situation, we need to use fragment. See the following code on how to include fragment in components.

“`

import { Fragment } from "react";
function ListGroup() {
 return (
   <Fragment>
     <h1>List</h1>
     <ul className="list-group">
       <li className="list-group-item">An item</li>
       <li className="list-group-item">A second item</li>
       <li className="list-group-item">A third item</li>
       <li className="list-group-item">A fourth item</li>
       <li className="list-group-item">And a fifth one</li>
     </ul>
   </Fragment>
 );
}
export default ListGroup;

“`

Rendering List : 

Previously we have the hard-coded list for rendering. Let’s render it dynamically.

  1. Let’s create a const variable where we will store a string which will be the names of items.
  2. Then we will use the map function as we cannot for loop inside the typescript. so this array will be traversed by the map function.
  3. Then we will remove all list elements from unorder list part.

“`

The final code will be on ‘ListGroup.tsx’.

import { Fragment } from "react";
function ListGroup() {
 const items = ["Rice", "Water", "salad", "curry"];
 return (
   <Fragment>
     <h1>List</h1>
     <ul className="list-group">
       {items.map((item) => (
         <li key={item}>{item}</li>
       ))}
     </ul>
   </Fragment>
 );
}
export default ListGroup;

“`

Conditional Rendering:

As we know that inside React Components we can’t use condition operator beside JavaScript XML, So we have to write a conditional statement inside curly braces ‘ {}’.

Here we have set the items variable empty. Then if you see you will find two conditional statements both output the same result but work in different ways. We will go second 

Option further if this kind of scenario happens.

Let’s understand Javascript AND operators. See the following example

  • true && 1
    Output => 1
  • true && “HI”
    Output => “HI”
  • false && 98
    Output => false

So from the above example, we can see that if one side of the AND operator is true then it returns the other side of the AND operator. If it’s false then return false that conditional statement.

** Notice that we have removed ‘<Fragment> </Fragment>’ and It’s import. React has a shorthand for ‘<Fragment> </Fragment>’ which is ‘<> </>’ and it doesn’t need to import anything. We have also added a bootstrap class which will beautify each row and add a padding margin **

The final code will be on ‘ListGroup.tsx’.

function ListGroup() {
 let items = ["Rice", "Water", "salad", "curry"];
 items = [];
 return (
   <>
     <h1>List</h1>
     {items.length === 0 ? <p>No item Found</p> : null}
     {items.length === 0 && <p>No item Found</p>}
     <ul className="list-group">
       {items.map((item) => (
         <li className="list-group-item" key={item}>
           {item}
         </li>
       ))}
     </ul>
   </>
 );
}
export default ListGroup;

Handling Events:

Here we will add an event listener to the list of every item. Every time we click an item it shows some details on the console log.

The final code will be on ‘ListGroup.tsx’.

function ListGroup() {
 let items = ["Rice", "Water", "salad", "curry"];
 return (
   <>
     <h1>List</h1>
     {items.length === 0 && <p>No item Found</p>}
     <ul className="list-group">
       {items.map((item, index) => (
         <li
           className="list-group-item"
           key={item}
           onClick={(event) => console.log(item, index)}
         >
           {item}
         </li>
       ))}
     </ul>
   </>
 );
}
export default ListGroup;

“`

But our previous event handling logic was one line so it was not messy as an inline function but if our logic gets more complex we should have go for another method which code is introduced below:

Here we have imported ‘mouseEvent’ from React because our event is outside react component so it doesn’t know which type of event it will have to handle.

The final code will be on ‘ListGroup.tsx’.

“`

import { MouseEvent } from "react";
function ListGroup() {
 let items = ["Rice", "Water", "salad", "curry"];
 //Event Handler
 const HandleClick = (event: MouseEvent) => console.log(event);
 return (
   <>
     <h1>List</h1>
     {items.length === 0 && <p>No item Found</p>}
     <ul className="list-group">
       {items.map((item, index) => (
         <li className="list-group-item" key={item} onClick={HandleClick}>
           {item}
         </li>
       ))}
     </ul>
   </>
 );
}
export default ListGroup;

“`

Managing State:

If we add a class name ‘active’ inside <li> tag we will find out that all lists are activated, All list items are Highlighted or Activated(blue).

For testing ‘ className=”list-group-item active” ’ add this line of code instead of 

‘ className=”list-group-item ” ’.

So this is not what we want, we want to highlight one item at a time.

Instruction and intuition for doing this are described below:

We can have a variable named ‘selectedIndex’ which will store the click index and by some logic, we will keep it highlighted. 

But react component is not aware of this variable and its changes. To solve this problem we have to tell react that this component is going to have a state or data that might change over time and to do that we have use one of the built-in functions of react is call ‘useState’.

This function (‘useState’) is called a Hook. A Hook is a function that allows us to tap into built-in features in react so this is called the state-hook.

Using this state-hook we can tell react that this component can have data or state that will change over time. Instead of declaring a variable we will use a state hook to initialize our variable.

“`

The final code will be on ‘ListGroup.tsx’.

import { useState } from "react";
function ListGroup() {
 let items = ["Rice", "Water", "salad", "curry"];
 const [selectedIndex, setSelectedIndex] = useState(-1);
 return (
   <>
     <h1>List</h1>
     {items.length === 0 && <p>No item Found</p>}
     <ul className="list-group">
       {items.map((item, index) => (
         <li
           className={
             selectedIndex === index
               ? "list-group-item active"
               : "list-group-item"
           }
           key={item}
           onClick={() => {
             setSelectedIndex(index);
           }}
         >
           {item}
         </li>
       ))}
     </ul>
   </>
 );
}
export default ListGroup;

“`

Passing data via Props:

So we were showing a list of items and its heading but if we want to show another list and its heading what will be the procedure? 

Again creating a list in code & its heading it’s not standard procedure so can we make our component reusable? So here comes Props or properties. Props are the inputs to our components so instead of defining items array there in ‘ListGroup.tsx’ file we will pass props from ‘App.tsx’.

To do this we have to decide the shape of our props which will pass in components. To do this we will use an interface. The interface is one of the TypeScript features to define the shape or interface of an object.

“`

The final code will be on ‘ListGroup.tsx’.

import { useState } from "react";
interface Props {
 items: string[];
 heading: string;
}
function ListGroup({ items, heading }: Props) {
 const [selectedIndex, setSelectedIndex] = useState(-1);
 return (
   <>
     <h1>{heading}</h1>
     {items.length === 0 && <p>No item Found</p>}
     <ul className="list-group">
       {items.map((item, index) => (
         <li
           className={
             selectedIndex === index
               ? "list-group-item active"
               : "list-group-item"
           }
           key={item}
           onClick={() => {
             setSelectedIndex(index);
           }}
         >
           {item}
         </li>
       ))}
     </ul>
   </>
 );
}
export default ListGroup;

The final code will be on ‘App.tsx’

import ListGroup from "./components/ListGroup";
function App() {
 let items = ["Dhaka", "Chattrogram", "Rangpur", "Khulna"];
 return (
   <div>
     <ListGroup items={items} heading="Cities" />
   </div>
 );
}
export default App;

“`

Passing Functions via Props:

So our list group item is working as we expected to do but in real world scenario something will expected to happen when a list item is selected, How to do it?

Here we will just ‘console.log’ list item names using the function. Function represents the real life something happening after clicking the list group item.

If we look at the prop object we see that we have already two properties, now we will write another property to output the item name in the ‘console.log’

“`

The final code will be on ‘App.tsx’

import ListGroup from "./components/ListGroup";
function App() {
let items = ["Dhaka", "Chattrogram", "Rangpur", "Khulna"];
const handleSelectItem = (item: string) => {
console.log(item);
};
return (
<div>
<ListGroup
items={items}
heading="Cities"
onSelectItem={handleSelectItem}
/>
</div>
);
}
export default App;

The final code will be on ‘ListGroup.tsx’.

import { useState } from "react";
interface Props {
 items: string[];
 heading: string;
 onSelectItem: (item: string) => void;
}
function ListGroup({ items, heading, onSelectItem }: Props) {
 const [selectedIndex, setSelectedIndex] = useState(-1);
 return (
   <>
     <h1>{heading}</h1>
     {items.length === 0 && <p>No item Found</p>}
     <ul className="list-group">
       {items.map((item, index) => (
         <li
           className={
             selectedIndex === index
               ? "list-group-item active"
               : "list-group-item"
           }
           key={item}
           onClick={() => {
             setSelectedIndex(index);
             onSelectItem(item);
           }}
         >
           {item}
         </li>
       ))}
     </ul>
   </>
 );
}
export default ListGroup;

“`

State vs Props:

Props State
Input passed to a component Data managed by a component
Similar to function args Similar to local variables
immutable mutable
Cause a re-render Cause a re-render

Passing Children:

It’s not same every time we will pass simple props like before, sometimes we have to pass props like HTML element etc.

For this react has introduced children as where we will use ‘’ for passing children to a component. React interface has a special key called children where we will pass ‘ReactNode’.’ReactNode’ will be able to handle HTML syntax as children in react component.

Follow the instructions written below: 

  1. Create file name ‘Alert.tsx’ under ‘components’ folder.
  2. Install an extension in vs code name ‘ES7+ React/Redux/React-Native snippets by dsznajder’ this will help to write code in shortcut.
  3. Then go to ‘Alert.tsx’ file start typing ‘rafce’ then press enter you will get a short code snippet for react component and its export.

If it doesn’t work don’t worry final code will be given below.

“`

The final code will be on ‘Alert.tsx’.

import { ReactNode } from "react";
interface Props {
 children: ReactNode;
}
const Alert = ({ children }: Props) => {
 return <div className="alert alert-primary">{children}</div>;
};
export default Alert;

The final code will be on ‘App.tsx’.

import Alert from "./components/Alert";
function App() {
 return (
   <div>
     <Alert>
       Hello <span> World </span>
     </Alert>
   </div>
 );
}
export default App;

“`

React Developer Tool:

Install “React Developer Tools” extension from your favorite web browser then explore different feature off from the inspection of your site. If you want to component hierarchy and if want to find out the props state you should use React Dev Tool.

#TASK – 1 : 

Create a Bootstrap button component.

  1. Button name will be Dynamic. 
  2. Button will be clickable, after clicking it will show ‘clicked’ in the console log.
  3. pass button className using props.

The solution is given below.

‘Button.tsx’ component will be..

interface Props {
 children: string;
 color: string;
 Onclick: () => void;
}
const Button = ({ children, color, Onclick }: Props) => {
 return (
   <div>
     <button type="button" className={"btn btn-" + color} onClick={Onclick}>
       {children}
     </button>
   </div>
 );
};
export default Button;

App.tsxcode will be..

import Button from "./components/Button";
function App() {
 return (
   <div>
     <Button
       children="primary"
       color="secondary"
       Onclick={() => console.log("clicked")}
     />
   </div>
 );
}
export default App;

#Task-2:

Create a Bootstrap alert using previous code where

  1. When click button it will show alert like before.
  2. In the alert component it should contain a dismissal button which will hide the alert component.

The solution is given below.

‘Alert.tsx’ component will be.

import { ReactNode } from "react";
interface Props {
 children: ReactNode;
 onClose: () => void;
}
const Alert = ({ children, onClose }: Props) => {
 return (
   <>
     <div className="alert alert-primary alert-dismissible ">
       {children}
       <button
         type="button"
         className="btn-close"
         data-bs-dismiss="alert"
         aria-label="Close"
         onClick={onClose}
       ></button>
     </div>
   </>
 );
};
export default Alert;

‘App.tsx’ component will be..

import { useState } from "react";
import Alert from "./components/Alert";
import Button from "./components/Button";
function App() {
 const [alertVisible, setAlert] = useState(false);
 return (
   <div>
    {alertVisible && <Alert onClose={() => setAlert(false)}>Alert</Alert>}
     <Button
       children="primary"
       color="secondary"
       Onclick={() => setAlert(true)}
     />
   </div>
 );
}
export default App;

In conclusion, learning React has been an exciting journey filled with endless possibilities for creating dynamic and interactive web applications. We have covered various fundamental concepts, explored advanced techniques, and delved into best practices along the way.

However, remember that learning is a lifelong process, and there is always more to discover. If you’re eager to further expand your knowledge of React, I highly recommend checking out the following resources:

Official React Documentation: The React website (https://react.dev/learn) is an invaluable resource for all things React. It provides comprehensive documentation, tutorials, and examples to help you dive deeper into the framework.

React Learning Roadmap: Roadmap.sh (https://roadmap.sh/react) offers a detailed and well-structured roadmap for learning React. It covers essential topics, recommended tools, and additional resources to guide you on your learning journey.

By leveraging these resources, you can continue to enhance your understanding of React, stay updated with the latest developments, and unlock new possibilities in building dynamic and performant applications.

Remember, practice makes perfect. Keep coding, exploring, and building exciting projects to solidify your React skills. Happy learning!

Contributor: Md. Mizanur Rahman, Software Engineer, Nascenia

Share it, Choose Your Platform!

More to Explore

The Quest for Knowledge Continues. Fuel Your Curiosity.