1

I know how to dynamically create react components based on lists, as the docs indicate. However, I want to create them dynamically but not together, with some strings in between. Specifically, I want to contain every regex in some custom components.

For example:

The cat is playing with the dog and the mouse

becomes

The <animal>cat</animal> is playing with the <animal>dog</animal> and the <animal>mouse</animal>

I know how to do the regex, but just adding the tags to the string would have them be still strings, instead of components.

1
  • do you have any code of what you've tried? Commented Feb 24, 2020 at 0:50

1 Answer 1

2

Return an array of strings and React components

import React from "react";

export default function App() {
  return (
    <div>
      {"The cat is playing with the dog and the mouse"
        .split(/(cat|dog|mouse)/)
        .map((x, i) => (i % 2 ? <Animal>{x}</Animal> : x))}
    </div>
  );
}

function Animal({ children }) {
  return <span style={{ color: "red" }}>{children}</span>;
}

https://codesandbox.io/s/nice-browser-950gx

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.