0

I am trying to add custom css to the placeholder within react text input field. The issue I have is I need multiple css attributes within a single placeholder(I'm not just setting all the placeholder to one new style). This is the output I am trying to achieve: eexample placeholder

Where some of the placeholder has a certain css and some of the placeholder is different.

This is all I have so far (no styles):

<form>
      <input class="bg-gray-100 w-full h-16 pl-5" type="text" placeHolder="Placeholder test" />
</form>
David Linder
  • 83
  • 1
  • 6
  • What you can do is to have custom structure of div and span and try to handle the same. – Mangesh Jun 24 '21 at 08:26
  • Do these answer your question? [Apply multiple styles to a single placeholder in an input element](https://stackoverflow.com/q/23007819/11613622), [Is it possible to have multiple text styling for an Input element's placeholder?](https://stackoverflow.com/q/53016731/11613622), [How can I style individual parts of an input placeholder?](https://stackoverflow.com/q/22655493/11613622), [Is there any way to change one word color of placeholder](https://stackoverflow.com/q/37699705/11613622) – brc-dd Jun 24 '21 at 11:14

1 Answers1

1

Put HTML elements directly on top of the input using CSS. Apply pointer-events: none to those elements. Add onFocus and onBlur behavior to the input. Control the hiding/showing of your placeholder content using local state. It should be hidden if the user is focused (your preference) or if there is text that already exists. Here is a small functional example. https://codesandbox.io/s/elated-galileo-k5zot

const Sample = () => {
    const [showPlaceholder, setShowPlaceholder] = React.useState(true)
    const [value, setValue] = React.useState('')
    const show = () => setShowPlaceholder(true)
    const hide = () => setShowPlaceholder(false)
    const update = (e) => setValue(e.currentTarget.value)
    return (
        <div style={{ position: 'relative' }}>
            {showPlaceholder && !value && (
                <div style={{ position: 'absolute', left: 5, top: 0, pointerEvents: 'none' }}>
                    <span>
                        custom {'  '}
                    </span>
                    <span style={{ color: 'red' }}>
                        element {'  '}
                    </span>
                    <span style={{ color: 'blue' }}>
                        here {'  '}
                    </span>
                </div>
            )}
            <input onFocus={hide} onBlur={show} onChange={update} />
        </div>
    )
}
Andrew
  • 7,201
  • 5
  • 25
  • 34