» npm install html-react-parser
React html parser not working with nexjts
Hello admin &a...
More on stackoverflow.comreactjs - Next.js - html-react-parser + <Image> solved Image aspect ratio - Stack Overflow
Next.js render app inside html markup coming as string
reactjs - Nextjs / React parse text to html format - Stack Overflow
I want manipulate an html strings, in vanillaJS I would do it something like this:
let HTMLString = '<p>hello</p> <style> p{color:black } </style> <p>world</p>'
const parser = new DOMParser();
const doc = parser.parseFromString(HTMLString, "text/html"); doc.querySelectorAll('style').forEach(item => item.remove())
this works in react aswell, but i believe since next compiles server side it just throws DOMParser is not defined, i've tried packages like html-react-parser, they just parse the html into react elements and offer very limited functionality after that, my last resort is using regex for this, but i've that's not a good idea.
any help in this would be good, thanks
You can achieve that with custom server,
const express = require('express')
const next = require('next')
const header = fs.readFileSync(path.resolve(ROOT + '/resources', 'header.txt'), 'utf8');
const footer = fs.readFileSync(path.resolve(ROOT + '/resources', 'footer.txt'), 'utf8');
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.all('*', async (req, res) => {
const nextResponse = await handle(req, res);
return mergeHTML(header, footer, nextResponse); // You will need to "merge" cause nextResponse has `head` & `body` as well.
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
mergeHTML should merge head from your header & next's head & the body. You can use cheerio to help you with that.
I solved the problem using dangerouslySetInnerHTML. Basically It does not care about the string syntax you pass into it, so I came up with the following solution in _document.js:
<Html>
<html dangerouslySetInnerHTML={{__html: header}}/>
<Head />
<body>
<Main />
<NextScript />
</body>
<html dangerouslySetInnerHTML={{__html: footer}}/>
</Html>
Both calls of dangerouslySetInnerHTML are taking the odd number of elements and wrapping around the next.js components.
By the was if anybody has an another solution maybe without dangerouslySetInnerHTML please comment it.