Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native what exactly is the <> (empty) component

In React Native you can encapsulate a set of components in one single <View> (or similar) component. You can also encapsulate a set of components as <> and </>. What are these? Do they just translate to an base View? It's probably not a good practice but it doesn't give a warning and it doesn't crash.

like image 469
Sander Koldenhof Avatar asked Jan 15 '20 12:01

Sander Koldenhof


People also ask

What is empty <> In React?

The React framework offers a shorthand syntax for fragment components that appears as an empty tag: <></> . While it is supported in JSX syntax, it is not part of the HTML standard and thus is not supported natively by browsers.

What is the use of <> In React?

Short Syntax You can use <></> the same way you'd use any other element except that it doesn't support keys or attributes.

Is <> same as React fragment?

<> is the shorthand tag for React. Fragment which allows us to group a list of elements without wrapping them in a new node. The only difference between them is that the shorthand version does not support the key attribute.

How do I know if React Native is empty?

To check if a string is empty in React, access its length property and check if it's equal to 0 , e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then the string is empty, otherwise it isn't empty.


2 Answers

It's the React shortcut for Fragment component.

You can write like this :

import React, { Component } from 'react'

class Component extends Component {
  render() {
    return <> <ComponentA/> <ComponentB/> </>
  }
}

Or without the shortcut and import Fragment component

import React, { Component, Fragment } from 'react'

class Component extends Component {
  render() {
    return <Fragment> <ComponentA/> <ComponentB/> </Fragment>
  }
}

You have to know, you can't use any key or prop with the shortcut syntax.

Here's the official documentation

I hope it helps !

like image 131
Hurobaki Avatar answered Sep 29 '22 00:09

Hurobaki


In addition to what He has said, it is used to embed many HTMLElements that you don't what them to be nested into a <div> for example.

For example, you may have this use cases

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

For more explanation you can read this React Official Documentation Fragment

like image 27
Patrissol Kenfack Avatar answered Sep 29 '22 01:09

Patrissol Kenfack