score:376
Yes you can, but instead of blank, simply return null
if you don't want to render
anything from component, like this:
return (null);
Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false
, you can return any of these values false, null, undefined, true
. As per DOC:
booleans (true/false), null, and undefined
are valid children, they will be Ignored means they simply don’t render.
All these JSX
expressions will render to the same thing:
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
Example:
Only odd values will get rendered, because for even values we are returning null
.
const App = ({ number }) => {
if(number%2) {
return (
<div>
Number: {number}
</div>
)
}
return (null); //===> notice here, returning null for even values
}
const data = [1,2,3,4,5,6];
ReactDOM.render(
<div>
{data.map(el => <App key={el} number={el} />)}
</div>,
document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app' />
score:0
We can return like this,
return <React.Fragment />;
score:0
Returning falsy value in the render() function will render nothing. So you can just do
render() {
let finalClasses = "" + (this.state.classes || "");
return !isTimeout && <div>{this.props.children}</div>;
}
score:2
for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!
i mean instead of this junk ternary condition inside your jsx in render part of your component:
// some component body
return(
<section>
{/* some ui */}
{ someCondition && <MyComponent /> }
or
{ someCondition ? <MyComponent /> : null }
{/* more ui */}
</section>
)
you can check than condition inside your component like:
const MyComponent:React.FC = () => {
// get someCondition from context at here before any thing
if(someCondition) return null; // i mean this part , checking inside component!
return (
<section>
// some ui...
</section>
)
}
Just Consider that in my case i provide the someCondition
variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition
inside MyComponent
.
Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:
// some component body
return(
<section>
{/* some ui */}
<MyComponent />
{/* more ui */}
</section>
)
and MyComponent
would handle the rest for you!
score:6
If you are using Typescript and your component/function has return type React.Element
, you will get the following error.
Type 'null' is not assignable to type 'ReactElement<any, string | JSXElementConstructor>'.
The solution is React.Fragment
.
return <React.Fragment />
or
return <></>
score:7
Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:
render = () => null
This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render
function and this is the most concise form satisfying this requirement that I can think of.
I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router
documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.
score:19
Yes you can return an empty value from a React render method.
You can return any of the following: false, null, undefined, or true
According to the docs:
false
,null
,undefined
, andtrue
are valid children. They simply don’t render.
You could write
return null; or
return false; or
return true; or
return <div>{undefined}</div>;
However return null
is the most preferred as it signifies that nothing is returned
score:40
Some answers are slightly incorrect and point to the wrong part of the docs:
If you want a component to render nothing, just return null
, as per doc:
In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.
If you try to return undefined
for example, you'll get the following error:
Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
As pointed out by other answers, null
, true
, false
and undefined
are valid children which is useful for conditional rendering inside your jsx, but it you want your component to hide / render nothing, just return null
.
EDIT React 18:
React 18 will allow rendering undefined
instead of throwing. See this announcement.
Source: stackoverflow.com
Related Query
- Is it possible to return empty in react render function?
- Return DOM element in render function of React component
- How to return an empty jsx element from the render function in react?
- In my custom React hook, Is it possible to write a function that can return a valid firebase query dynamically?
- How can I return a React Component from a function and render it onClick?
- Is it possible to create a function inside react render that contains an if statement to setState
- return function doesn't render in React
- React JS state array empty inside function but items appear in render
- dynamically render the array at different labels inside return function react js
- Return from an IF statement inside of a react render function
- React signup page syntax error at return of render function
- React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing
- React onClick function fires on render
- Is it possible to use if...else... statement in React render function?
- Access React Context outside of render function
- Functions are not valid as a React child. This may happen if you return a Component instead of from render
- Render Content Dynamically from an array map function in React Native
- React component children detect if empty / null before render
- Does a render happen before function in React Hooks useEffect is called?
- React Context: TypeError: render is not a function
- React hooks: call component as function vs render as element
- Possible to render react component within mapboxgl.Popup() in .setHTML or .setDOMContent?
- Typescript React empty function as defaultProps
- Early returns in React sub render function: return null, [], or React.Fragment?
- Using react hooks inside render prop function
- Invariant Violation in React Render OR the proper way to iterate and return in React
- Unit testing: react context api with enzyme return an empty object
- Can a cellRenderer function in ag-Grid return a React component?
- { React jsx babel es6 webpack } How Can I Comment in render ( return ( // || /**/ ) )?
- How to return a React memoized callback from factory function
More Query from same tag
- Antd table how to fixed first row
- redux store not getting updated and component not rerenders
- Weird setState behaviour with MaterialUI in React JS
- How import object from external JS file in React JS using web pack
- Pass state from class component to function component in react
- measure state update from within event handler function
- Why isn't the undo variable updated?
- Why won't my require() inside my img work correctly while using it with Bulma?
- Bind icon images to their respective names then render
- React day picker return all data when expecting only day
- onClick doesn't work while trying to render: reactjs, basic API fetch
- Render components vertically rather than horizontally
- Material-UI center button text ignoring icons
- react container not being removed on re-render
- Req.files to hold file objects in multiple arrays
- React-Select trigger onChange when value changes
- Why isn't favicon shown up in production?
- How to properly export a component from a React custom hook and a function to control it?
- React Semantic UI Table Cell Does not Respond to onClick
- How to add curson style "not-allowed" to Material UI datagrid disabled row?
- sibling selector with :before doesn't work in styled-component?
- How to render a self-destructing paragraph at mouse position in React?
- Unable to move handle on a react slider using cypress
- Why does React skip over the last question that is correctly set to state?
- issues normalizing data using normalizr react
- Add empty table rows to a Table until it has a certain number of rows
- How to reference pdf.js library in React?
- How to update the image when state is updated?
- Why are React defaultProps not passing values?
- catch block isn't getting my errors from the fetch api