ReactJS Fragments, Import and Export Components

ReactJS Fragments, Import and Export Components

ReactJS Fragments

We know that we use the render method inside a component whenever we want to render something to the screen. We may render single or multiple elements, though rendering multiple aspects will require a ‘div’ tag around the content as the render method will only render a single root node inside it at a time. 

To solve this problem, React introduced Fragments from the 16.2 and above version. Fragments allow you to group a list of children without adding extra nodes to the DOM.

Syntax:

Components Export and Import in React

Every piece of UI element is called a component in React. A component is reusable things. React components are regular JavaScript functions with some exceptions. Component names always begin with a capital letter. Component return JSX markup.

How can Export and Import a Component?

Two primary ways you can export a component.

  1. default export

  2. named export

Default export

A file can have no more than one default export. This type of export is commonly used when a file exports only one component.

You can import the component in another file like this:

Note that the name Message is arbitrary and can be changed to anything you like

Named Exports

A file can have as many named exports as you like. Named exports are used when a file exports multiple components or values

To use these functions in another file, we need to import them using the same names and curly braces:

Alternatively, we can use the * symbol to import all the named exports from a file as an object, which is very similar to other languages like Python and Java

When to use named export and when to use default export?

  • Use named export when you want to export multiple variables or functions from a file.

  • Use default export when you want to export only one variable or function from a file.

  • Use named export when you want to keep the same name for your variables or functions across different files.

  • However, it's important to note that you can use both default and named exports in the same file.

Thank You So Much Bikash Karki Sir :)

#learnig #MERN #React #NMC #Day3

To view or add a comment, sign in

Others also viewed

Explore topics