Search code examples
reactjstextareanextuidangerouslysetinnerhtml

dangerouslySetInnerHTML not working in NextUI


I am new to NextUI and React. I need to add html into a textarea because I will add some highlighted substrings, but the html is interpreted as plain text.

Below is my current code. I tried using dangerouslySetInnerHTML, but the text is still being rendered as plain text instead of html. What I am doing wrong?

export default function Home() {

const text1 = '<a>foo</a>';

return (

<div className="flex flex-col w-full mb-6 md:mb-0 gap-4">

    <div className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4">
        <Textarea
            isReadOnly
            label="ID 1"
            labelPlacement="outside"
            value={text1}
            dangerouslySetInnerHTML={{ __html: text1 }}
            size="lg"
            className="resize-y min-h-[200px]"
            minRows={18}
            maxRows={18}
        />
    </div>

    <div className="flex justify-center gap-6 w-full mt-4">
        <Button color="success" variant="ghost" size="md">Yes</Button>
        <Button color="danger" variant="ghost" size="md">No</Button>
    </div>
</div>
);

}


Solution

  • I'm not familiar with NextUI, but the NextUI Textarea apparently renders an HTML textarea, which can only contain plain text, and doesn't render HTML code.

    So there is nothing you can do.

    dangerouslySetInnerHTML just puts the HTML code inside the innerHTML of the element, so this is basically the same as trying to add HTML code inside a textarea in a normal HTML page, with is not supported. Like:

    <body>
        <textarea>
            HTML code in `textarea` is <b>not</b> supported.
        </textarea>
    </body>