15

I'm new to reactjs. I'm trying to put a condition in the render return method to show component. I'm getting the following error.

./components/Layouts/Header.js
SyntaxError: /home/user/Desktop/pratap/reactjs/society/society-front/components/Layouts/Header.js: Unexpected keyword 'this' (14:8)

  12 |   render() {
  13 |     return (
> 14 |       { this.props.custom ? <CustomStyle /> : <DefaultStyle /> }
     |         ^
  15 |     );
  16 |   }
  17 | }

Here is my component code -

import React from "react";
import CustomStyle from "./CustomStyle";
import DefaultStyle from "./DefaultStyle";

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custom:this.props.custom
    }
  }
  render() {
    return (
      { this.props.custom ? <CustomStyle /> : <DefaultStyle /> }
    );
  }
}

export default Header;
Mahendra Pratap
  • 3,174
  • 5
  • 23
  • 45

1 Answers1

20

You can't return a ternary operator when you are explicitly returning JSX, Wrap your code in a Fragment:

  render() {
    return (
      <>{ this.props.custom ? <CustomStyle /> : <DefaultStyle /> }</>
    );
  }

Or remove the separator:

render(){
    return this.props.custom ? <CustomStyle /> : <DefaultStyle />
}
Dupocas
  • 20,285
  • 6
  • 38
  • 56