React: Expanding render() method behaviour

Created on 5 Apr 2017  ยท  4Comments  ยท  Source: facebook/react

Regular render() method behaviour

Everytime we render a component we have to place it within a element-wrapper. Let's say this element is a div with CSS class myDiv.

import React, {Component} from 'react';

class RregularRenderBehaviour extends Component {
  render() {
    return (
      <div className="myDiv">
        <p className="myParagraph">Hi!</p>
        <p className="myParagraph">Hi!</p>
        <p className="myParagraph">Hi!</p>
     </div>
    );
  }
} 

Extended render() method behaviour

Maybe it's better to pass render() method two parametres:

  1. An element that will wrap up our jsx code that is returned (div) ;
  2. A CSS class that will be assigned to an element-wrapper (myDiv).
    Here is an example of what I am trying to say.
class ExtendedRenderBehaviour extends Component {
  render(div, "myDiv"){
    return (
        <p className="myParagraph">Hi!</p>
        <p className="myParagraph">Hi!</p>
        <p className="myParagraph">Hi!</p> 
    );
  }
}

If render() method didnt receive any parametres It will wrap jsx code with a div by default.

I think this enhancement can save time a bit and you dont have to worry that u didnt wrap your jsx code.

All 4 comments

How is this better? What problem is it solving?

@vijaybritto I think second option saves time and u dont have to worry that you didn't place your jsx code inside an element.

I've updated description a bit. Thank You, this was an important comment.

render(div, "myDiv") {
 // ...
}

This is a method definition, not a function call. It receives parameters when it is called from some other place, but you can't pass values to the definition like that.

A render() method in an ES6 class is similar to a function in an object like this, which may be more clear:

var obj = {
  render: function (x, y) { // โ† you can't do `function (div, "className") {`!
  }
}

I'm not sure I understand the utility of your particular suggestion, but React 16 will allow returning arrays ("fragments") from the render method. I think this should satisfy your use case.

Was this page helpful?
0 / 5 - 0 ratings