1

I currently have:

let renderEmailField = ({input, label, type, meta: {touched, error, pristine}}) =>
  <div>
    <label>{label}</label>
    <Form.Input {...input} type={type} placeholder={'name@example.com'} />
    {touched && error && <span className="form-control-feedback">{error}</span>}
  </div>

How can I update the above to not require to surrounding DIV?, something like:

let renderEmailField = ({input, label, type, meta: {touched, error, pristine}}) =>
    <label>{label}</label>
    <Form.Input {...input} type={type} placeholder={'name@example.com'} />
    {touched && error && <span className="form-control-feedback">{error}</span>}
halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

3 Answers3

1

If you are using any version of React before before version 16 you are not able too as each component must return only one element. If you use/upgrade to React 16 you have the ability to do what you are asking in your question i.e. returning an array of dom elements, a string or a number from a component.

 render() {
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>,
    <li key="C">Third item</li>,
  ];
}

See https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings

Geraint
  • 3,314
  • 3
  • 26
  • 41
1

You could just return an array:

let renderEmailField = ({input, label, type, meta: {touched, error, pristine}}) =>
  [
    <label>{label}</label>
    <Form.Input {...input} type={type} placeholder={'name@example.com'} />
    {touched && error && <span className="form-control-feedback">{error}</span>}
  ]

But you will still have to return a single component from your render method, so for example, if renderEmailField is the top-level rendering component, you'd have to still wrap it in a <div>:

render() {
  return (
    <div>
      {this.renderEmailField()}
    </div>
  )
}

Unless you update to React 16 which supports rendering arrays of components.

nem035
  • 34,790
  • 6
  • 87
  • 99
0

Your question boils down to Can you return multiple values from a function in Javascript?

The answer is no. You can only return one value, in your case an html element, from your function; hence the surrounding div is required.

In React 16, they have added support for returning arrays as stated in the other answers.

palsrealm
  • 5,083
  • 1
  • 20
  • 25