'insert divs inside a string to make nested strings of code then render them in React Js
I'm receiving an SQL query as a string and an array of line numbers and indexes of start and end. I have to extract sub queries and render them nested inside each other. I have to make each sub query clickable and copy its text when clicked. What I did was splitting the SQL string into lines then I used three loops to wrap each sub query in a div according to the line and index start and line and index of the end.
This is the array of arrays. Each array contains two arrays one with the line number and index number of the start and the second is for the end line and index number.
const chunks = [
[
[3, 0],
[32, 248],
],
[
[11, 8],
[24, 23],
],
[
[32, 22],
[32, 247],
],
[
[32, 108],
[32, 152],
],
[
[32, 166],
[32, 216],
],
[
[34, 0],
[62, 248],
],
[
[42, 8],
[55, 23],
],
[
[62, 22],
[62, 247],
],
[
[62, 108],
[62, 152],
],
[
[62, 166],
[62, 216],
],
[
[63, 0],
[94, 83],
],
[
[75, 7],
[76, 64],
],
[
[78, 10],
[91, 25],
],
]
This is the loop to insert divs to wrap each sub query:
for (let i = 0; i < chunks.length; i++) {
for (let c = 0; c < 2; c++) {
for (let x = 0; x < codeChunks.length; x++) {
if (x === chunks[i][c][0] - 1) {
var b = `<div className="sub-query query_${i}">`
var stringLeft = (
codeChunks[x].slice(0, chunks[i][c][1])?.match(/layer/g) || []
)?.length
let countLength
if (stringLeft === 0) {
countLength = 0
} else {
countLength = stringLeft * b.length
}
let position
if (c === 0) {
position = chunks[i][c][1] + countLength
} else {
position = chunks[i][c][1] + countLength + 1
}
if (c === 0) {
codeChunks[x] = [
codeChunks[x].slice(0, position),
b,
codeChunks[x].slice(position),
].join("")
} else {
codeChunks[x] = [
codeChunks[x].slice(0, position),
"</div>",
codeChunks[x].slice(position),
].join("")
}
}
}
}
}
I tried different packages to parse strings into JSX but the problem is they don't accept inline functions and I get an error when I add a ref that says cannot use strings as refs. Can anyone help me realize the idea ? I hope it is clear
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
