Reputation: 679
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>;
}
}
Upvotes: 3
Views: 778
Reputation: 673
Hi Ozil,
Go ahead and give this snippet a try to see if this is what you are trying to achieve, pal! let us know the outcome on your end!
const domEl = document.getElementById("container");
ReactDOM.render(<RemoveTabs />,domEl);
function RemoveTabs() {
let text ="Once upon a time, \t there was a man \t who had a house.";
return(<div>{"<div>"+text.replace(/\t/g,'</div><div>')+"<div>"}</div>);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>
<div id="container"></div>
Upvotes: 1
Reputation: 3063
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.
Upvotes: 2