Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textarea preview like stackoverflow have

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?

like image 517
IcanCode Avatar asked Nov 01 '25 12:11

IcanCode


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>
like image 191
Anonymous Panda Avatar answered Nov 04 '25 03:11

Anonymous Panda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!