I achieved converting a piece of string into a component
function App() {
const text = "Please make sure this is BUTTON";
const modText = text.replace(/ /g, ", ");
const parts = modText.split(",");
const mapped = parts.map((part) => {
return part.match(/BUTTON/) ? <button>{part}</button> : part;
});
return <div>{mapped}</div>;
}
but the output in the image looks really weird when I combine it back
I wanted it to become one sentence again something like
just one sentence not with " " every word
CodePudding user response:
You can do it like this:
function App() {
const text = "Please make sure this is BUTTON";
const parts = text.split(/(BUTTON)/);
const mapped = parts.map((part,i) => i&1 ? <button key={i}>{part}</button> : part || null);
return <div>{mapped}</div>;
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
CodePudding user response:
You'll need to join() the array to get a string.