1

STATIC CONTENT

Place a character at the end of the word. And once user key in, the H will still remain closed to every words.

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState } from "react";

export default function App() {
  const [val, setVal] = useState("Hello");
  return (
    <div className="App">
      <div>
        <div>
          <input
            type="text"
            value={val}
            onChange={(e) => setVal(e.target.value)}
          />
          <span>
            H
          </span>
        </div>
      </div>
    </div>
  );
}

Honey Singh
  • 362
  • 8

2 Answers2

1

To add a text suffix to an element, the simplest solution is to use CSS content on an ::after pseudo-element (instead of writing complicated JS calculations):

.example {
  display: inline-flex;
  align-items: center;
}

.example::after {
  content: "H";
  font-size: 2rem;
  font-weight: 900;
  /* add margin-left if needed */
}
<span class="example">Hello</span>
<br>
<span class="example">Hello Why Are You So Close</span>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

Here is the solution: https://codesandbox.io/s/loving-orla-wfljwe?file=/src/App.js

Inspired by: Auto-scaling input to width of value in React

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState, useRef, useEffect } from "react";

export default function App() {
  const [val, setVal] = useState("!Hello World ^_^");

  const [width, setWidth] = useState(0);
  const span = useRef();
  useEffect(() => {
    setWidth(span.current.offsetWidth);
  }, [val]);

  return (
    <div className="App">
      <div className="input-group position-relative">
        <div className="form-floating">
          <span
            ref={span}
            style={{
              position: "absolute",
              opacity: 0,
              zIndex: -1000,
              whiteSpace: "pre"
            }}
          >
            {val}
          </span>
          <input
            type="text"
            value={val}
            onChange={(e) => setVal(e.target.value)}
            className="form-control"
          />
          <span
            className=""
            style={{
              position: "absolute",
              top: "0.7rem",
              left: `${width + 16}px`,
              color: "red",
              fontSize: "34px",
              fontWeight: "bold"
            }}
          >
            {val.substring(0, 1).toUpperCase()}
          </span>
        </div>
      </div>
    </div>
  );
}
Serj Woyt
  • 46
  • 3