apps/mantine.dev/src/pages/core/json-input.mdx
import { JsonInputDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';
export default Layout(MDX_DATA.JsonInput);
JsonInput is based on the Textarea component.
It includes JSON validation logic and an option to format the input value on blur:
Set loading prop to display a loading indicator. By default, the loader is displayed on the right side of the input.
You can change the position with the loadingPosition prop to 'left' or 'right'. This is useful for async operations like API calls, searches, or validations:
import { useState } from 'react';
import { JsonInput } from '@mantine/core';
function Demo() {
const [value, setValue] = useState('');
return <JsonInput value={value} onChange={setValue} />;
}
JsonInput can be used with uncontrolled forms the same way as a native textarea element.
Set the name attribute to include json input value in FormData object on form submission.
To control the initial value in uncontrolled forms, use the defaultValue prop.
Example usage of uncontrolled JsonInput with FormData:
import { JsonInput } from '@mantine/core';
function Demo() {
return (
<form
onSubmit={(event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
console.log('JSON input value:', formData.get('data'));
}}
>
<JsonInput
label="Enter JSON"
name="data"
defaultValue="{}"
formatOnBlur
/>
<button type="submit">Submit</button>
</form>
);
}
You can provide custom serialize and deserialize functions to support data formats beyond standard JSON.
This is useful when you need to handle types like Date, Map, Set, undefined, or other non-JSON-serializable values.
The example below shows how to use superjson library to handle extended data types:
import { useState } from 'react';
import { JsonInput } from '@mantine/core';
import superjson from 'superjson';
function Demo() {
const [value, setValue] = useState(
superjson.stringify(
{
name: 'John Doe',
createdAt: new Date(),
tags: new Set(['admin', 'user']),
metadata: new Map([['role', 'developer']]),
},
null,
2
)
);
return (
<JsonInput
label="Extended JSON with superjson"
description="Supports Date, Map, Set, BigInt, RegExp, and more"
placeholder="Enter extended JSON"
value={value}
onChange={setValue}
serialize={(val) => superjson.stringify(val, null, 2)}
deserialize={superjson.parse}
validationError="Invalid extended JSON format"
formatOnBlur
autosize
minRows={6}
/>
);
}
The deserialize function must throw an error when the input is invalid. Both serialize and deserialize
functions are used for formatting when formatOnBlur is enabled.