Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!