Comments (1)
Hey @aayush-makwana ,
If I understood correctly, you need a way to handle large input text using material-ui library.
Here, in the snippet below I have added three types of input:
- This is a static width text and add ellipsis to very long placeholder text.
- This is a dynamic width text, where width is dependent on the provided placeholder.
- This is also a dynamic width text, where width is dependent on the input provided by user. It changes input size when the user adds/removes a character.
Filename: App.js
import React from 'react';
import TextFieldComponent from './TextFieldComponent';
import { Box } from '@mui/material';
function App() {
return (
<div className="App">
<header className="App-header">
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: '100vh',
gap: 2, // Optional: adds space between the elements
padding: 2
}}
>
<TextFieldComponent label={'This is a static width text input with ellipsis to support long placeholder'} />
<TextFieldComponent dynamicWidth={'placeholder'} label= {'This is a dynamic width text input. Width changes as you increase/decrease the placeholder text'} />
<TextFieldComponent dynamicWidth={'input'} label= {'This is a dynamic width text input. Width changes as you type in the input'} />
</Box>
</header>
</div>
);
}
export default App;
Filename: TextFieldComponent.js
import React, { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import {TextField,FormLabel, Typography } from '@mui/material';
import Box from '@mui/material/Box';
// Component to render a text field with dynamic width and label value
const TextFieldComponent = ({ dynamicWidth, label }) => {
const [value, setValue] = React.useState('');
const [inputWidth, setInputWidth] = useState(100);
const spanRef = useRef(null);
// Effect hook to update the input width based on the dynamic width if it equates to 'placeholder' only
useEffect(() => {
if (dynamicWidth && spanRef.current) {
if(dynamicWidth === 'placeholder') {
setInputWidth(spanRef.current.offsetWidth + 40);
}
}
}, [dynamicWidth]);
// Function to handle changes in the text field's value. It updates the value. Also based on dynamic width value it updates the input width conditionally.
const handleChange = (event) => {
setValue(event.target.value);
if(dynamicWidth === 'input') {
setInputWidth(40 + getTextWidth(value));
}
};
// Function to calculate the width of a given text string by creating a temporary span element, calculating its width and then removing it from DOM.
const getTextWidth = (text) => {
// Create a hidden Typography component to measure the width
const hiddenTypography = (
<Typography
variant="body1"
style={{
position: 'absolute',
visibility: 'hidden'
}}
>
{text}
</Typography>
);
// Create a div element to render the hidden Typography component
const div = document.createElement('div');
document.body.appendChild(div);
// Render the hidden Typography component to the div
ReactDOM.render(hiddenTypography, div);
// Get the width of the rendered Typography component
const width = div.firstChild.offsetWidth;
// Remove the div from the DOM
document.body.removeChild(div);
return width;
}
return (
<Box sx={{ marginY: 2 ,display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',}}>
{dynamicWidth && (
<span
ref={spanRef}
style={{
visibility: "hidden",
position: "absolute",
whiteSpace: "nowrap",
fontFamily: "Roboto, Arial, sans-serif",
}}
>
{label}
</span>
)}
<FormLabel>{label}</FormLabel>
<TextField
label={label}
variant="outlined"
value={value}
onChange={handleChange}
sx={{ width: dynamicWidth ? inputWidth : 'auto' }}
/>
</Box>
);
};
export default TextFieldComponent;
Hope this helps!
from material-ui.
Related Issues (20)
- [material-ui][Autocomplete] Non-fixed width Autocomplete resizes on hover HOT 1
- [material-ui][Select] Wrong placement when using a custom icon HOT 2
- [material-ui][table] Aligning expandable parent and child rows HOT 2
- [icons] Not finding the DialerSip icon HOT 1
- [material-ui] Composing a theme with multiple `experimental_extendTheme` calls throws error
- [material-ui][TextField] When with minRows, it makes the height from small to final height HOT 3
- Support for enabling checkboxes only for leaf nodes
- [docs][pigment-css] Add opt-in migration to Pigment CSS
- [material-ui][Text FIeld] Outlined variant label is broken
- [docs] Material Icon Imports wrong in docs
- [joy-ui][Tooltip] Not working with custom sub-components
- [material-ui][Select] Cycle On Focus Without Having Options Open HOT 1
- [material-ui][TablePagination] TablePagination component throws `You have provided an out-of-range value `4` for the select component.` warning HOT 1
- Using material ui styles with remix v2
- {...other} would overwrites the ownerState
- [RFC] Any Roadmaps or Plans for fully support for Next.js App Router and Server Components?
- [docs] Change dark theme component background color without affecting other states
- [core] Adopt eslint-plugin-react-compiler
- [material-ui] Textfield add autoSelect prop HOT 3
- When trying to link an application using MUI v5, application gets "TypeError: Cannot read properties of null (reading 'useContext')"
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from material-ui.