Fernando Chu
Fernando Chu

Reputation: 383

React, how to dynamically create components inside a string?

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.

Upvotes: 1

Views: 50

Answers (1)

lissitz
lissitz

Reputation: 546

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

Upvotes: 2

Related Questions