I have a component in react js project which displays some text. the text variable is of type string and has some tab escape charcters within. I would like to replace this tab character and use a div . how do i replace this with a
such that when it renders , it outputs the div within the when it renders HTML. so on the page source in browser i see something like this => <span> once upon a time, <div> there was a man <div> who had a house. </span>
text = "once upon a time, \t there was a man \t who had a house." ;
class somcomponent extends React.Component {
render() {
return <span> {text}</span>;
}
}
You can split your text by \t and render a div each split, like this:
class somcomponent extends React.Component {
render() {
return <span>
{text.split('\t').map(s=><div>{s}</div>)}
</span>
}
}
In a snippet:
const rootElement = document.getElementById("root");
ReactDOM.render(
<Demo />,
rootElement
);
function Demo() {
let text = "once upon a time, \t there was a man \t who had a house." ;
return (
<span>
{text.split('\t').map(s=><div>{s}</div>)}
</span>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
text.split('\t') will split your text into a list of strings that are between '\t'.
Now, use map to render <div>{s}</div> for each element in that list, while s is current string you're iterating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With