cssreactjstextareastylingautosize

Add styling to defaultValue in textarea in React


I am using a Material UI React component called TextareaAutosize:

<TextareaAutosize
  minRows={2}
  style={resize: 'none'}
  defaultValue={<span style={{fontSize: "20px", color: "blue"}}>Content Body</span>}
/>

Instead of getting Content Body in the TextareaAutosize component, I'm getting this as the default value:

enter image description here

How do I add styling to the defaultValue?

Edit code on Stack Blitz: https://stackblitz.com/edit/react-fnx6we?file=demo.js

EDIT: For clarification, I want ONLY the defaultValue to have the styling I applied. When the user starts typing or removes the defaultValue and starts typing, the styling of the defaultValue should NOT be applied.


Solution

  • defaultValue parameter accepts String values only. Use parameter style to define additional styling. Or use jss like styling for components (check @mui/styles) EDIT: to change styling of the element "on the fly" you will need to use additional variables and functions. Check demo on code on Stack Blitz.

    import React, { useState } from 'react';
    import TextareaAutosize from '@mui/material/TextareaAutosize';
    import { makeStyles } from '@mui/styles';
    
    const useStyles = makeStyles({
      textAreaWithStyle: {
        background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
        border: 0,
        borderRadius: 3,
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
        color: 'white',
        height: 48,
        padding: '0 30px',
        fontSize: '20px',
        color: 'blue',
        resize: 'none',
      },
      textAreaWithoutStyle: {
        resize: 'none',
      },
    });
    
    export default function MaxHeightTextarea() {
      const classes = useStyles();
      const [valueOfInput, setValueOfInput] = useState('Default Text');
    
      const returnStyleBasedOnInput = () => {
        if (valueOfInput === 'Default Text') {
          return classes.textAreaWithStyle;
        } else {
          return classes.textAreaWithoutStyle;
        }
      };
    
      const checkIfDefaultValueInTextAreaAndRemooveIt = () => {
        if (valueOfInput === 'Default Text') {
          setValueOfInput('');
        }
      };
    
      const onInputChange = (e) => {
        setValueOfInput(e.target.value);
      };
    
      return (
        <TextareaAutosize
          maxRows={4}
          className={returnStyleBasedOnInput()}
          value={valueOfInput}
          onChange={onInputChange}
          onClick={checkIfDefaultValueInTextAreaAndRemooveIt}
        />
      );
    }
    

    Edit code on Stack Blitz: https://stackblitz.com/edit/react-fnx6we-3vdn7i?file=demo.js