Home > Blockchain >  Why do react components as class must have `render` method, while those as functions don't?
Why do react components as class must have `render` method, while those as functions don't?

Time:12-19

When I write a component as class, it needs the render method. For example:

class Greet extends React.Component {
  render() {
    return <h1>Hello, world!</h1>;
  }
}

As a result, render() is a method of every Greet instance. Meanwhile, if I write the same component as a factory function, the render() method isn't required:

function Greet() {
  return <h1>Hello, world!</h1>;
}

In both cases, to render that component in the browser window, it's needed to run this:

ReactDOM.render({ 
  <Greet />,
  document.getElementById("root")
});

So, how come that when a class is passed as a parameter to ReactDOM.render(), it needs render() to be included, while a function doesn't?

Is it, by any chance, because the class can't directly return something without encapsulating it in a method, so it was decided for that method to have the same name? In that case, how does the ReactDOM.render() work in the each scenario?

CodePudding user response:

Function can not have any other functions, so that's why it "the render() method isn't required". Meanwhile classes can have multiple other methods, so React must know beforehand what method to call, so that's why it requires render in class.

Imagine interfaces in other languages where you can implement classes whatever you want, but must have predefined set of methods

CodePudding user response:

In React think of a functional component as been the render part of a class. A lot of times, especially when using composition, that's often all a React component needs to do. So this really does cut down on a lot of boiler plate.

But then that leaves a big hole, like how you handle lifecycle / effect methods etc, and that's were Hooks come in.

So then back to your question => needs render() to be included

You are kind of correct, if you mean a class (constructor) can't return something, well it can, but it's not advised to do so. And since in React render can be called multiple times, it certainly wound't make sense for it to be in the constructor anyway.

So in a nutshell, since a functional React component is the render stage, it of course doesn't require a render function. But since a class constructor shouldn't be used for a render function, it will of course need a render method..

  • Related