Git Product home page Git Product logo

Comments (1)

suraj-anthwal avatar suraj-anthwal commented on June 27, 2024

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:

  1. This is a static width text and add ellipsis to very long placeholder text.
  2. This is a dynamic width text, where width is dependent on the provided placeholder.
  3. 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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.