Given a react component like below (https://jsfiddle.net/69z2wepo/28684/):
var Hello = React.createClass({
render: function() {
let { cond, name } = this.props;
let content, content2;
if (cond){
content = (<div>Hello { name } </div>);
content2 = (<div>content 2</div>);
}
return (
<div>
{ content }
{ content2 }
</div>
)
}
});
ReactDOM.render(
<Hello name="World" cond={ true } />,
document.getElementById('container')
);
How can I achieve something like:
content += (<div>content 2</div>) //not working
and then render the content in a single content variable instead of both content and content 2?
Use a template literal to concatenate strings and variables in React, e.g. "<a href={ https://example.com/${myPath} }". Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.
Rendering an Element in React: In order to render any element into the Browser DOM, we need to have a container or root DOM element. It is almost a convention to have a div element with the id=”root” or id=”app” to be used as the root DOM element.
render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element. But render where? There is another folder in the root directory of your React project, named "public".
var Hello = React.createClass({
render: function() {
let { cond, name } = this.props;
let content, content2, contents;
if (cond){
content = (<div>Hello { name } </div>);
content2 = (<div>content 2</div>);
contents = [content, content2];
}
return (
<div>
{ contents }
</div>
)
}
});
ReactDOM.render(
<Hello name="World" cond={ true } />,
document.getElementById('container')
);
https://jsfiddle.net/69z2wepo/28687/
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