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

2 Answers 2

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>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Now that is what I am looking for. Amazingly done. Thank you so much. You are the rockstar.
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>

1 Comment

Wow. It is a simple answer. Nice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.