React Importing and Exporting Components - GeeksforGeeks (2024)

Last Updated : 01 Mar, 2024

Summarize

Comments

Improve

React Importing and Exporting Components are two major operations that enable the re-use of the components to create a collection of components and hence a complete application.

Table of Content

  • Importing and Exporting React Components
  • Importing a React Component
  • Exporting a React Component
  • React Importing and Exporting Components Example:

Importing and Exporting React Components

We have learned so far that React Apps are a collection of interactive Components, and from the article, on React Components. we know how to create components but even with that knowledge, it will not be sufficient to create a full-fledged React App. To do so we need to know two operations broadly known as Importing and Exporting.

We may not have told earlier, but we have been using the import operation in every one of our previous articles when we were importing react and react-dom itself. Similarly, we can also import user-defined classes, components, or even a part of the same. Let us shift our discussion over Importing.

Importing a React Component

The world of JavaScript is always moving and one of the latest ES2015 now provides a more advanced module importing/exporting pattern. In previous engines, the developer had to use the module.exports = { // Define your exports here. }, but now with ES2015 every module can have a default export or may export several named parameters, and if it is possible to export it will surely be possible to import the same. Thus, with ES2015 every module may import the default export or several named parameters or even a valid combination.
React uses the same features as mentioned above, and you may treat each React Component as a module itself. Thus, it is possible to import/export React Components, and is one of the basic operations to be performed. In React we use the keyword import and from to import a particular module or a named parameter.

Let us now see the different methods of importing ReactJS components.

Importing default export:

Every module is said to have at most one default export. In order to import the default export from a file, we can use only the address and use the keyword import before it, or we can give a name to the import making the syntax as the following.

import GIVEN_NAME from ADDRESS

Importing named values:

Every module can have several named parameters and in order to import one we should use the syntax as follows.

import { PARA_NAME } from ADDRESS

Similarly, for multiple such imports, we can use a comma to separate two-parameter names within the curly braces.

Importing a combination of Default Exports and Named Values:

The title makes it clear what we need to see is that the syntax is the same. In order to import a combination, we should use the following syntax.

import GIVEN_NAME, { PARA_NAME, ... } from ADDRESS

Note: When importing we sometimes come across files that have .js extensions like Color.js, when importing we can follow any of the below-given syntaxes:

import Color from './Color.js'
// OR
import Color from './Color'

In the above syntax both the codes work correctly because ES Modules working allows importing in both the ways

Exporting a React Component

Now, importing is an operation that requires the permission of the module. Importing is possible only if the module or named property to be imported has been exported in its declaration. In React we use the keyword export to export a particular module or a named parameter or a combination.

Let us now see the different ways we can use the export operation in React.

Exporting default export:

We have already learned that every module is said to have at most one default export. In order to export the default export from a file, we need to follow the syntax described below.

export default GIVEN_NAME

Exporting named values:

Every module can have several named parameters and in order to export one we should use the syntax as follows.

export { PARA_NAME }

Similarly, for multiple such exports, we can use a comma to separate two-parameter names within the curly braces.

React Importing and Exporting Components Example:

Let us see it in the example below where we would use the import and export operations in several ways. Let there be two files, one index.js, and the other change-color.js. Let us see how to implement the import and export operations.

javascript

// Filename - src/index.js

// Importing combination

import React, {Component} from 'react';

// Importing Module

import ReactDOM from 'react-dom';

import ChangeColor from './change-color.js';

// Importing CSS

import './index.css';

class App extends Component {

render()

{

return (<div><h2>Welcome to</h2>

<ChangeColor title="GeeksforGeeks" /></div>);

}

}

ReactDOM.render(

<App/>,

document.getElementById('root')

);

This is the change-color.js file exporting component as default export:

javascript

// Importing combination

import React, {Component} from 'react';

class ChangeColor extends Component {

constructor(props)

{

super(props);

this.state = { color : '#4cb96b' };

}

getClick()

{

if (this.state.color === '#4cb96b')

this.setState({ color : '#aaa' });

else

this.setState({ color : '#4cb96b' });

}

render()

{

return <h1 style = { this.state }

onClick = {this.getClick.bind(this)}>

{this.props.title} < /h1>

}

}

// Exporting the component as Default export

export default ChangeColor;

Output:

React Importing and Exporting Components - GeeksforGeeks (1)

Explanation:

The codes above generate the following App which on clicking the “GeeksforGeeks” changes the text color of it. It is illustrated in the figure below.

Now apparently we have completed all the basic requirements to create a basic yet presentable app of our own. Stay tuned to create one for yourself.



P

PronabM

React Importing and Exporting Components - GeeksforGeeks (2)

Improve

Next Article

How to import components in React Native ?

Please Login to comment...

React Importing and Exporting Components - GeeksforGeeks (2024)
Top Articles
Why Google search results have 'gotten worse'
A Day In The Life of A Professional Forex Trader
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 5672

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.