Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append element to variable to be render in react

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?

like image 729
mystic Avatar asked Jan 24 '16 13:01

mystic


People also ask

How do you append variables in React?

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.

How do I render an element in React?

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.

How do you use render () in React?

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".


1 Answers

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/

like image 71
Raghvendra Parashar Avatar answered Sep 22 '22 02:09

Raghvendra Parashar