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.
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>;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.