How to make readonly mui textfield in Next.js

Cover Image for How to make readonly mui textfield in Next.js
Ali Bentaleb

In this tutorial, we are going to explain how to make an mui textfield read only

This tutorial can be used in a React based app like Next.js

In short, to make an mui textfield readonly, which means you can not alter its value, you can either :

  • Set key readOnly to true for prop InputProps

the syntax is as follow

<TextField InputProps={{readOnly: true}} defaultValue="Hello World" />

or

  • Use prop disabled and set it to true

the syntax is as follow

<Textfield disbaled defaultValue="Hello World" />

The difference is that with the first method, text is written in bold, the latter is not, but in both of them you can not alter text. So you can use any of those that you feel comfortable with

Material UI (MUI) readonly sample

Now, let’s see a sample in Next.js on how to use textfield with readonly prop

If you have not install mui yet or have trouble doing it, you can check my article for mui package installation

Create pages/test.js and copy the following code

import {TextField} from '@mui/material';

export default function Test() {
	return (
		<form className="p-2 flex flex-col w-1/3">
			<TextField
				id="someId"
				label="Email"
				defaultValue="Hello World"
				disabled
			/>
		</form>
	);
}

The inline CSS used is tailwindcss, you can also use your own classes or use these classes after installing tailwindcss, [this article][1] will help you install it

Test validation

Now when you run localhost:3000/test you notice that the default value is printed, and you can not change it

mui email textfield validation

You can also change disabled and put inputProps={{readOnly:true}} and notice that text is becoming bold and you can not change its value as well

Conclusion

We have seen how to make read only mui textfield .

If you like to work with mui, check also this article which will help you better understand mui, with samples on how to use buttons, texfields and customize them.

How to use Material UI (MUI) T...How to validate Mui TextField ...