Search code examples
reactjsconcatenationjsx

How to concatenate two JSX fragment or variables or string and component (in Reactjs)?


I know JSX can be very misleading because it looks like strings and it is not, thus the "string" term in the question, even if we are not really manipulating strings.

Here is a code example (wrong, obviously):

let line = <Line key={line.client_id} line={line}/>;
if(line.created_at) {
    return <div className="date-line"><strong>{line.created_at}</strong></div> + line;
} else {
    return chat_line;
}

I have a line, and I want to "concatenate" some divs in front of it under certain conditions. What would be the proper syntax? I've tried parenthesis, brackets, plus sign... None of them seem to work...

thanks


Solution

  • Use arrays:

    let lineComponent = <Line key={line.client_id} line={line}/>;
    if (line.created_at) {
      return [
        <div key="date" className="date-line"><strong>{line.created_at}</strong></div>,
        lineComponent,
      ];
    } else {
      return chat_line;
    }
    

    Or use fragments:

    import createFragment from "react-addons-create-fragment";
    
    let lineComponent = <Line key={line.client_id} line={line}/>;
    if (line.created_at) {
      return createFragment({
        date: <div className="date-line"><strong>{line.created_at}</strong></div>,
        lineComponent: lineComponent,
      });
    } else {
      return chat_line;
    }
    

    In both cases, you have to provide keys for React. In case of array, you set key directly on element. Regarding fragments, you provide key:element pairs.

    NOTE: When returning from render method, you can only return single element, or NULL. Examples provided are invalid in that case.