React: custom render method doesn't return the input-label pair

Viewed 128

ANSWERED.

EDIT: This was a silly mistake and I was trying out StackOverflow.

I have a private render method, to render a pair of label and input.

However, it is not rendering anything. I have tried out almost everything and cannot figure out the reason.

Here is the render method:

const _renderLabelInputPair = (labelValue = '', inputProps = {}) = {
  <>
    <label>{labelValue}</label>
    <input {...inputProps} />
  </>
}
5 Answers

Easiest way to clear this confusuion:

Round Braces => Wraps something to be returned
Curly Braces => Wraps a block.

Remember one of these and you are good to go!

You have not returned anything from the function.

You can do one of the following:

  1. Replace the curly braces with round braces.

  2. Add a return to the funtions, which return the whole element (jsx).

In react functional components, React expects you to return something.

const _renderLabelInputPair = (labelValue = '', inputProps = {}) = {
  return <>
    <label>{labelValue}</label>
    <input {...inputProps} />
  </>
}

I recommend you create a separate component instead of a function that returns the JSX.

It will increase your code readability and will be easier for maintaining.

You can either include a return keyword. Or use round brackets as a shorthand to return from arrow functions.

Also, there's a typo - change the = to =>

const _renderLabelInputPair = (labelValue = '', inputProps = {}) => {
  return <>
    <label>{labelValue}</label>
    <input {...inputProps} />
  </>
}

OR

const _renderLabelInputPair = (labelValue = '', inputProps = {}) => (
  <>
    <label>{labelValue}</label>
    <input {...inputProps} />
  </>
)}
Related