textarea preview like stackoverflow have

Viewed 54

I have a textarea, I created a preview div which only displays the text, but I want the text to have background color of grey when the sentence is between `` to display codes.

<textarea onChange={handleChange}></textarea>

I have a div which contains pre and code block.

<div>
 <pre>{preview}</pre>
 <code>{code}</code>
</div>

my handleChange function is:

const handleChange = (e) =>{
    e.preventDefault()
    setDescription(e.target.value)
    setPreview(e.target.value);

    if (e.key === '`'){
      setCode(e.target.value)
    }

}

Here, Code and preview are defined using useState

const [preview, setPreview] = useState("");
const [code, setCode] = useState("");

Is there any way I can accomplish it?

1 Answers

You should probably consider using some library for this that handles all edge cases.

But for learning purposes you can refer to the snippet below, I've split the text by ` and wrapped all the odd index items in code.

When you split the string "type `code` here", you get this array ["type", "code", "here"] and if you observe the contents wrapped inside ` will always be at an odd index. So, I've mapped over the array and wrapped all odd index items within code. Try spitting more such strings and you'll get more clarity on this.

function App() {
  const [content, setContent] = React.useState("Type `code` here");

  return (
    <div>
      <textarea
        value={content}
        onChange={({ target }) => setContent(target.value)}
      ></textarea>
      <p>
        {content
          .split("`")
          .map((c, i) => (i & 1 ? <code key={i}>{c}</code> : c))}
      </p>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
code {
  background: #eee;
  padding: 0.25rem;
  border-radius: 0.15rem;
}

textarea {
  width: 60ch;
  height: 5rem;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>

Related