Skip to content
Advertisement

Is there a way to manipulate rendered text in react component children?

I am trying to write a component that highlights text inside it’s children recursively.

What I have been able to achieve, is to highlight the text only if it’s explicitly provided in the body component, but I can’t find a way to change the text of the component’s render part.

Let’s say I have the following HighlightText component:
(Note, that this is a concept component. The real component is much more complicated)

JavaScript

And some component that renders something:

JavaScript

Now, I want to use the HighlightText component the following way:

JavaScript

The resulted DOM of the the above code is:

JavaScript

But I expect it to be:

JavaScript

Any suggestions on how to handle the rendered part of the child component?

Advertisement

Answer

Eventually I managed to solve this problem using React.Context.

Not exactly as I expected, but I think it’s even a better approach, because now I can decide what text to highlight.

It’s similar to i18n and themes techniques in React. React.Context is best approach for these kind of text manipulations.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement