Connecting React, MUI & TypeScript Together

Snehasish Konger
Level Up Coding
Published in
6 min readApr 7, 2023

--

React MUI TypeScript is a combination of three powerful technologies used in front-end development: React, Material-UI, and TypeScript.

React, a JavaScript library developed by Facebook, is widely used for building user interfaces and single-page applications. It offers the advantage of reusable components, streamlining the development process.

Material-UI, on the other hand, is a React library that follows Google’s Material Design guidelines. It comes with a wide range of pre-built UI components that can be easily customized using CSS.

TypeScript, a superset of JavaScript, adds optional static typing to the language. This increases the reliability and maintainability of codebases, especially in larger projects with multiple developers or frequent changes. The type annotations in TypeScript also make it easier for developers to understand the structure and behavior of a codebase.

The combination of React, Material-UI, and TypeScript provides numerous benefits for web application development. The reusable components in React, paired with the pre-built UI components in Material-UI, lead to faster and more visually appealing user interfaces. The static typing in TypeScript helps identify errors early in the development process, making it easier to spot and fix bugs. The type annotations in TypeScript also enhance code clarity, especially in large or complex projects. Overall, the combination of React MUI TypeScript leads to the creation of reliable, maintainable, and visually appealing web applications.

In this guide, we will walk through the process of building a project using React, Material-UI and Typescript.

Syntax:

import React from 'react';
import { Button } from '@material-ui/core'; // to import Material UI button
const HelloWorld = () => {
return <div>
<Button> // MUI button
Click me!
</Button>
...
</div>;
}
export default HelloWorld;

Steps to Initialize a new project

Step 1: To start, we need to create a new project directory and initialize it with npm. You can do this by running the following command in your terminal:

mkdir my-project
cd my-project
npm init -y

This will create a new directory called my-project and initialize it with a default package.json file.

Step 2: Installing dependencies

Next, we need to install the dependencies required for our project. We will be using Material-UI as our UI library, so we need to install it along with its required dependencies. We will also be using Typescript, so we need to install it as well.

npm install @material-ui/core @material-ui/icons typescript @types/react @types/react-dom

This will install Material-UI, its icons, Typescript, and the required types for React and React-DOM.

Here is the package.json file where we can see the dependecies.

Step 3: Setting up Typescript

Now that we have installed all the required dependencies, we need to set up Typescript for our project. To do this, we need to create a new file called tsconfig.json in the root of our project directory.

touch tsconfig.json

Open the tsconfig.json file in your text editor and add the following code:

{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": ["src"]
}

This is a basic configuration for Typescript that will allow us to use it in our project.

File Structure

Here is the file structure we will be using for this project(CSS and other files are not added here):

Creating the components

In the src/components directory, we will create three components: Task, TaskList, and TaskForm.

The “Task.tsx” component will display a single task with a title and a description. It will also have a button to delete the task.

import React from 'react';
import { IconButton, Typography } from '@material-ui/core';
import { Delete } from '@material-ui/icons';
interface TaskProps {
id: number;
title: string;
description: string;
onDelete: (id: number) => void;
}
const Task: React.FC<TaskProps> = ({ id, title, description, onDelete }) => {
return (
<div>
<Typography variant="h5">{title}</Typography>
<Typography>{description}</Typography>
<IconButton onClick={() => onDelete(id)}>
<Delete/>
</IconButton>
</div>
);
}
export default Task;

The TaskList component will display a list of tasks. It will receive an array of tasks and a callback function to delete a task.

import React from 'react';
import Task from './Task';
interface TaskListProps {
tasks: { id: number; title: string; description: string }[];
onDelete: (id: number) => void;
}
const TaskList: React.FC<TaskListProps> = ({ tasks, onDelete }) => {
return (
<div>
{tasks.map((task) => (
<Task
key={task.id}
id={task.id}
title={task.title}
description={task.description}
onDelete={onDelete}
/>
))}
</div>
);
}
export default TaskList;

The TaskForm component will display a form to add or edit a task. It will receive a callback function to submit the form and a task object to edit.

import React, { useState } from 'react';
import { TextField, Button } from '@material-ui/core';
interface TaskFormProps {
onSubmit: (title: string, description: string) => void;
task?: { title: string; description: string };
}
const TaskForm: React.FC<TaskFormProps> = ({ onSubmit, task }) => {
const [title, setTitle] = useState(task ? task.title : '');
const [description, setDescription] = useState(task ? task.description : '');
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit(title, description);
};
return (
<form onSubmit={handleSubmit}>
<TextField
label="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
fullWidth
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
fullWidth
/>
<Button type="submit" variant="contained" color="primary">
Submit
</Button>
</form>
);
}
export default TaskForm;

Creating the Home page

In the src/pages directory, we will create the Home page.

The Home page will display the TaskList and TaskForm components. It will also have a state to keep track of the tasks and callback functions to add, edit, and delete tasks.

import React, { useState } from 'react';
import TaskList from '../components/TaskList';
import TaskForm from "../components/TaskForm";
const Home: React.FC = () => {
const [tasks, setTasks] = useState([
{ id: 1, title: 'Task 1', description: 'This is task 1' },
{ id: 2, title: 'Task 2', description: 'This is task 2' }
]);
const addTask = (title: string, description: string) => {
setTasks([...tasks, { id: tasks.length + 1, title, description }]);
};
const editTask = (id: number, title: string, description: string) => {
const newTasks = [...tasks];
const index = newTasks.findIndex((task) => task.id === id);
newTasks[index] = { id, title, description };
setTasks(newTasks);
};
const deleteTask = (id: number) => {
setTasks(tasks.filter((task) => task.id !== id));
};
return (
<div className='App'>
<TaskList tasks={tasks} onDelete={deleteTask} />
<TaskForm onSubmit={addTask} />
</div>
);
}
export default Home;

Creating the main App component

In the src directory, we will create the App component. This component will render the Home and About pages based on the current URL path using the react-router-dom Route component.

import React from 'react';
import Home from './pages/Home';
const App: React.FC = () => {
return (
<div className="App">
<Home />
</div>
);
}
export default App;

And now, finally we’ll write the index.tsx.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));

Run the Application:

To run the task management application, you need to first ensure that you have all the required dependencies installed. You can do this by running the command:

npm install

Once the dependencies are installed, you can run the application using the following command:

npm start

This will start a development server and open the application in your default web browser. The development server will automatically reload the application when you make changes to the code.

Here is the final result:

Now, if you like the content and want to read more content like this don’t forget to follow me.

Here you can get the source code.

Also, if you like reading coding-related stuff, then please take a look at my website: Scientyfic World. There I talk about some amazing stuff.

--

--