David Linder
David Linder

Reputation: 83

How to customise react / next.js input placeholders

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>

Upvotes: 0

Views: 2245

Answers (1)

Andrew
Andrew

Reputation: 7555

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>
    )
}

Upvotes: 1

Related Questions