Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between render and return in reactjs?

I am new to JavaScript. I see lot of places return and render being used just want to know what's the difference between them.

like image 382
vinod kumar Avatar asked Mar 02 '18 23:03

vinod kumar


People also ask

Why render and return in React?

Essentially render is kind of a lifecycle method which is invoked whenever the component needs to update. As for the return statement, its used to return the data/response/JSX elements depending on where it is used.

What is render in Reactjs?

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

What is the return type of render in React?

Regardless of what a component ends up rendering, React. createElement always returns an object, which is the JSX.

Does render return?

Remember that the render method in your controllers is not returning the control flow from your action and you can still modify the response or perform some operations once you call render . You only cannot call render more than once in a single action as that will raise the DoubleRenderError exception.


1 Answers

render method is required when you are writing a React component using as a class method

According to the docs:

The render() method is required.

When called, it should examine this.props and this.state and return one of the following types:

React elements. Typically created via JSX. An element can either be a representation of a native DOM component (<div />), or a user-defined composite component (<MyComponent />).

String and numbers. These are rendered as text nodes in the DOM.

Portals. Created with ReactDOM.createPortal. null. Renders nothing.

Booleans. Render nothing. (Mostly exists to support return test && pattern, where test is boolean.)

Essentially render is kind of a lifecycle method which is invoked whenever the component needs to update.

As for the return statement, its used to return the data/response/JSX elements depending on where it is used. If used in render method you need to return one of the above specified types(React elements, Strings and numbers, Portals or Booleans).

return from other function can either return the value evaluated from the function or return the React elements to be rendered in the render method

Functional components don't define a render method, instead they return the React elements using an explicit return statement or an implicit return

Eg: explicit return

const Welcome = (props) => {   return <h1>Hello, {props.name}</h1>; } 

Eg: Implicit return

const Welcome = (props) => (      <h1>Hello, {props.name}</h1>; ) 
like image 73
Shubham Khatri Avatar answered Sep 21 '22 12:09

Shubham Khatri