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= "w3wiki" /></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:
Explanation:
The codes above generate the following App which on clicking the “w3wiki” 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.
React Importing and Exporting Components
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: