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.
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.
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.
Regardless of what a component ends up rendering, React. createElement always returns an object, which is the JSX.
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.
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
andthis.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>; )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With