-
-
Notifications
You must be signed in to change notification settings - Fork 134
Add Current Node Index in replace
Callback
#1240
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
replace
Callbackreplace
Callback
Try transform(reactNode, domNode, index) {
if (domNode instanceof Element && domNode.type === "script") {
return React.cloneElement(reactNode, { id: `${fixedID}-${index}` });
}
return reactNode;
} |
it worked, thanks a lot for your help. |
@yaman3bd it shouldn't cause performance issues since both calls are executed in the same block: https://github.com/remarkablemark/html-react-parser/blob/v5.0.11/src/dom-to-react.ts#L47-L58 |
Update: I released a version that added the index as the 2nd argument in |
Problem
I'm working with
HTML/JS
code fetched from a CMS. This code may contain multiple scripts. I'm usingnext/script
which requires each script to have a unique id. However, when there are many scripts, it's challenging to assign the correct id since the scripts are dynamically mounted.Here's how I'm currently handling scripts:
I could assign a unique id to each script, but this would require handling many cases and tracking which script has the current id and which script is currently mounting to avoid id duplication.
so I’ve come up with this solution:
I can’t use
useMemo
in scripts because it’s not in a React component or a hook. So, each time a re-render happens, the scripts will be recalculated. Also, I think that looping through the DOM to filter only the script tags and map them into an index may cause performance issues because thehtml
may be large or contain many elements, and each time a re-render happens, the code will run again.Suggested Solution
the best solution is adding the current node index as a parameter in
replace
callback. so I can easily have a unique id and have smth like:const cacheKey = ${fixedID}-${index}
.Keywords
next/script
, dynamic script handling, unique id, replace.The text was updated successfully, but these errors were encountered: