Does a React Component require Render props?

Viewed 446

I have a simple react component....

const TestTemplate = ()=> (
    <h1>Hello World</h1>
)

I have been told this isn't a real component because it would need to accept render props but I am not using them. According to the docs

A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

The with here is key to me it means a component may or may not have a render prop. Is this true or am I wrong? Does it need to be this to be valid?

const TestTemplate => (props)=>(
    <h1>Hello World</h1>
)
2 Answers

It's not that it has to accept props, but that it needs to be a function or a class that extends React.Component. The first example is just JSX, it is not a component because it is not a function that returns JSX.

It would be perfectly valid to change it to this:

// Does not expect a `props` object, but is a functional component
const TestTemplate = () => (
  <h1>Hello World</h1>
)

The second example is also syntactically incorrect. The first arrow should just be an equal sign since its an assignment of a const.

You can read more about components here in the docs.

I think you're also misunderstanding what a "render prop" is. A render prop is a prop that contains JSX (or a function that returns JSX). It is not referring to the entire props object that can be passed into a component, but rather a type of prop.

For example, it may look something like this:

const Parent = () => {
  const renderProp = () => (<div>I'm from a render prop</div>);

  return <Child renderProp={renderProp} />
}

const Child = (props) => {
  return props.renderProp();
}

ReactDOM.render(<Parent />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

This pattern can be used several different ways, but this is the basic idea.

Needs to be a function or a class

A real react component needs to be a function or a class. You do not need to pass props for it to be a component.

The top example you gave is just a variable with some jsx inside, not a real component.

Related