Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a React Component require Render props?

Tags:

reactjs

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>
)
like image 461
JGleason Avatar asked May 11 '26 06:05

JGleason


1 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.

like image 177
Brian Thompson Avatar answered May 12 '26 22:05

Brian Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!