cbdeveloper
cbdeveloper

Reputation: 31485

Can I style only a specific part of an html input's string value?

Can I style just part of an input's value?

Like in this following example (snippet below), can I style just the "@user" part in bold and let the "some other content" unaltered?

enter image description here

If that's not possible, I'm thinking of using a div with contexteditable. It's a different approach, but would it work?

function App() {
  const [value,setValue] = React.useState('@user some other content...');
  
  function handleChange(e) {
    setValue(e.target.value);
  }
  
  return(
    <input 
      style={{width:'300px'}}
      type='text'
      value={value}
      onChange={handleChange}
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Views: 802

Answers (1)

charlietfl
charlietfl

Reputation: 171690

Form controls render text only. Styling parts of a string requires html

You would need to wrap parts of string to style in <span>

Start of string <span style="color:red">substring to style</span>

and put it in an html containing element

Upvotes: 2

Related Questions