-2

I've got the following code:

const CoolComponent = props => { ...

and I want to define a render() function to it:

render() {
    console.log('Hello world');
    return (
      <Bar
        foo={true}
        {...propz}
      />);

But when I try to add render() to CoolComponent it says there's parsing error (expecting new line or semicolon) in render() {. Is CoolComponent a React Component after all? Or if it's just a function, how I can combine it with a Bar component to reuse all the props?

A. Karnaval
  • 727
  • 2
  • 8
  • 12
  • 1
    You cannot add render to stateless react components, just return jsx code without render. – Janiis Jul 12 '19 at 17:12
  • 2
    Reread [the explanation of functional components](https://reactjs.org/docs/components-and-props.html#function-and-class-components), which is pretty clear on the what and why. @Janiis: technical correction (which for React is pretty important), functional components were never technically stateless, but with the `useState` hook being an official thing now, we _really_ can't call them stateless anymore. (a bit pedantic, but for React, and technical terms in general, pedantry is kind of essential to make sure we don't confuse people) – Mike 'Pomax' Kamermans Jul 12 '19 at 17:26

2 Answers2

0

Functional component do not have lifecycle hooks. So, here you just use the return statement or implicit return using parentheses () instead of curly brace {} and return statement, which will render the component:

const CoolComponent = props => {
   return (
     <Bar
       foo={true}
       {...propz}
     />
   )
}

The preceding example of code has issue with the props. See below for proper example.

Also, when you have the props with the value of true, you can just simply use the props. Here's what I would use simply:

const CoolComponent = props => {
  const { foo, ...rest } = props
  return <Bar foo {...rest} />
}

Or,

const CoolComponent = ({foo, ...rest}) => {
  return <Bar foo {...rest} />
}

Or even one line with your example:

const CoolComponent = ({foo, ...rest}) => <Bar foo {...rest} />

Single line statement will only be valid when you don't have multi line of code.


Implicit return with multiline of code:

const CoolComponent = ({foo, ...rest}) => (
   <div>
    <Bar foo {...rest} />
   </div>
)

You may also read my another post explaining about implicit and explicit return.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

You only have two option. Option 1: Use the class like this.

class MainComponent extends React.Component{
  render(){
    return(
      <div>Hello World!</div>
    );
  }
}

Option 2: Use the function like this.

const MainComponent = props => {
  return (
    <div>Hello World!</div>
  )
}
Tri Nguyen
  • 397
  • 3
  • 5
  • 18