Correct way (if possible) to store JSX code into a Javascript variable

20,473

Solution 1

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

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

Solution 2

Use () around JSX that spans multiple lines

var href = this.props.submenu ? 'javascript:' : (<Link to="mod/admin" + this.props.link />);
Share:
20,473
Mendes
Author by

Mendes

BY DAY: Working hard to turn ideas into borderline software BY NIGHT: Family, fun, barbecue and rockn´roll - go to sleep and brand new ideas again... C++, Javascript, MEAN, ReactJs, Relay and naturally C++ (never missing it) Forerunner into future.... http://stackrating.com/badge/Mendes

Updated on July 05, 2022

Comments

  • Mendes
    Mendes almost 2 years

    I´ve written the following code using ReactJs´s JSX syntax:

    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 it seend that I cannot store a direct JSX code into a variable, as 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 the href variable ?

  • kamikazeOvrld
    kamikazeOvrld over 7 years
    Sorry about that, I actually hadn't closely seen what exactly you were trying to achieve, what exactly are you trying to assign to href? You also have an opening parenthesis after the = sign, and you never close it
  • jdunning
    jdunning about 6 years
    Parentheses aren't required to split JSX tags across multiple lines.