Reputation: 3135
I save more strings inside an array. What I want to do is to show them when hover over an icon each of them on separate lines. What I tried so far:
addMessages = () => {
const text = [];
//add strings in the array
return text.join("<hr/>");
}
render() {
const showWhenHover = this.addMessages();
return (
<ActionBar popover={<div> {showWhenHover}</div>}
<div>
<Icon type="myIcon"/>
</div>
</ActionBar>
);
}
}
When I hover over the icon it shows the messages but not each of them on a separate line but all in one line like this:
text1</hr>text2</hr>text3
Isn't <hr/>
what must be used in this case? Thanks
Upvotes: 1
Views: 11008
Reputation: 2349
text.join
will render a single string, including <hr />
in this case. In order to render JSX instead, try:
addMessages = () => {
const text = [];
// add strings in the array
return text.map((item, index) => (
<span key={index}>
{item}
{index && <hr />}
</span>
));
}
Only downside here is the extra span, but I would prefer this over using dangerouslySetInnerHTML
.
Upvotes: 3
Reputation:
You can also use return text.map(e => <div>{e}</div>);
to get each string in its own line.
function addMessages() {
const text = [];
text.push("1st line");
text.push("2nd line");
text.push("Third line");
text.push("And a final one");
return text.map(e => <div>{e}</div>);
}
const App = () => <div>{addMessages()}</div>
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Upvotes: 0
Reputation: 8552
Your function addMessage generates strings and not a html markup.
One solution is to use template literals allow multiline strings. The other thing is that make sure that the text are contained within an element that has defined dimensions, or dimensions big enough that the text can go to the next line.
const genText = () => `
Text with lots of
spaces within
it blah blah blah
blah
`
const Comp = () => <div style={{width: 100, height: 200}}>{genText()}</div>
ReactDOM.render(<Comp />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Upvotes: 4