The correct way (if possible) to save JSX code in a Javascript variable

I wrote the following code using the syntax ReactJs´s JSX:

import { Link } from 'react-router';

class SidebarMenuItem extends React.Component {

render() {

    var href = (this.props.submenu ? 'javascript:' : {<Link to="mod/admin" + this.props.link />};

    return ( 

        <a href={href} onClick={this.selected}>
            <i className={'fa ' + this.props.icon} />
            <span>{this.props.title}</span>
        </a>

    )
  }
}

But this means that I cannot store direct JSX code in a variable, since I got the following error:

Module build failed: SyntaxError: D:/9. DEV/client/components/App/SidebarMenuItem.js: Unexpected token, expected , (41:52)

  40 | 
> 41 |      var href = (this.props.submenu ? 'javascript:' : {<Link to="mod/admin" + this.props.link />};
     |                                                        ^

What is the correct way to store my Link component in a variable href?

+4
source share
2 answers

you just write plain jsx, in your case you need to remove the brackets around jsx and then include the brackets around the "mod / admin" + this.props.link part just like you would when writing to the rendering method.

var href = this.props.submenu ? 'javascript:' : <Link to={"mod/admin" + this.props.link} />
+3
source

() JSX,

var href = this.props.submenu ? 'javascript:' : (<Link to="mod/admin" + this.props.link />);
+2

Source: https://habr.com/ru/post/1668326/


All Articles