Hey, everyone, welcome back to another post by Appsloveworld. In today’s post, we’ll be learning all about the most basic infrastructure of ReactJs components.
So we’ll be touching on topics like what are components, types of components, nesting components, higher-order and pure components.
what exactly are components?
Components are the building blocks of react application, wherein each component represents a part of the user interface. Now to make it more understandable. Consider the below web epage.
The entire UI can be broken down into several elements. Say we have the header component, the sign up component, the hotel search component and the deal component. Notice that each component add something to how the home page looks.
- Reusability is one of the salient features of the React components. One component can be reused several times across the application and this improves the development speed.
- Components can also be nested – One component can internally consist of several other components. In its minimal form a component must define a render method that specifies how exactly the application looks and feels.
- A component can also get properties from its parent components. you’ll get a better understanding of all these when we start working hands on. So don’t worry.
So moving on, let’s look at the different types of components
- Functional Components
- Class Components
First, we have the stateless functional components and then we have the stateful class components.
Now Let’s understand Functional components
Functional components are typically JavaScript functions that return HTML.They can be contained in a .JS OR JSX files.
import React from 'react' function Myfunctionalcomp() { return <b>Hello this is functional Component</b> } export default Myfunctionalcomp;
Now Let’s understand class components
Coming to class components. These are regular ES6 classes. However, it’s mandatory that they contain a render() method that return html.they can also be contained in .JS OR JSX File.
import React, { Component } from "react"; class Myclasscomp extends Component { render() { return <b>Hello this is class Component</b> } } export default Myclasscomp;
let’s go ahead and build our first application using components. All right, so I’ve opened my text editor i.e VS code to build my application.
Also, I suggest you read the React installation on Windows to help you get started. The post briefly explains how to install node and how to start building your first React application.
In my case, here in my source folder. I have App.js, Now App.js is the main component that gets rendered to the DOM.
Here in index.js ,in which you pass App.js, which is a component that gets rendered to the react dom.
So App.js Consists of several other components that can be nested. So as you can see, App.js is a functional component.
And before moving on, let me get rid of all the unnecessary code. And return , that says, “hello, welcome to Appsloveworld”. let save it and if we look at the browser. we will have , hello, welcome to Appsloveworld .
import logo from './logo.svg'; import './App.css'; function App() { return ( <h1>Hello, welcome to Appsloveworld</h1> ); } export default App;
Now let’s go ahead and display another message.
import logo from './logo.svg'; import './App.css'; function App() { return ( <h1>Hello, welcome to Appsloveworld</h1> <h1>React Js Tutorial</h1> ); } export default App;
And let save it and let check the browser. It gives you an error. JSX uses a conventional tool which states that all HTML Tags have to be enclosed within Div tag.
So multiple HTML TAGS have to be enclosed within the div tag. So let’s enclose it within <div> tag. So let save and check again.
import logo from './logo.svg'; import './App.css'; function App() { return ( <div> <h1>Hello, welcome to Appsloveworld</h1> <h1>React Js Tutorial</h1> </div> ); } export default App;
Moving on, let’s create the first functional component, to do that. I first create a folder in my src folder, say components within that I create a file myfunctionalcomp.js.
So the first thing we have to do is import React. So I say import React from ‘react’;
General syntext for the functional component involves, the keyword function and component.
Now you say return message “Hello this is login screen”.
import React from 'react' function myfunctionalcomp() { return <b>Hello this is functional Component</b> }
How components are exported and imported
Before explaining to you , how these components are exported and imported, let me show you the general syntax for class component. So I create another file myclasscomp.js.
The general notation is using the class keyword, followed by the name of the class extending from the base class Component. Now the key feature of a class component is the usage of a render method.
I say return <b>Hello this is functional Component</b>
import React, { Component } from "react"; class myclasscomp extends Component { render() { return <b>Hello this is class Component</b> } }
All right, so moving on, let’s see how these components can be nested into the main component that is in App.js.
Components can be nested into the main components using import and export keywords.
As the name suggests, export features use to export a particular file or a module and import is used to import a particular file or module into the current existing module.
So we have two different types of exports. You have default export and just export or named export.
So a default export is used to export just one object, be it a function, class, variable from the file and there can only be one default export per file.
when you’re importing it. You can specify the address and use the word import before it. So let me show you how it works.
import React from ‘react’;
Let’s go back to our functional component .And here I say export default and the name of the functional component i.e Myfunctionalcomp. So let me save this.
import React from 'react' function Myfunctionalcomp() { return <b>Hello this is functional Component</b> } export default Myfunctionalcomp;
And going back to app.js, I say import name, the functional component that is Myfunctionalcomp from and I pass path.
Now let’s define functional component in our app.js components. So here I see myfunctionalcomp. Let’s compile it and check our browser here. It says “Hello this is functional Component”.
import logo from './logo.svg'; import './App.css'; import Myfunctionalcomp from "../src/components/Myfunctionalcomp"; function App() { return ( <div> <h1>Hello, welcome to Appsloveworld</h1> <h1>React Js Tutorial</h1> <Myfunctionalcomp></Myfunctionalcomp> </div> ); } export default App;
Moving on to class component. It’s the same syntax here as well.
import logo from './logo.svg'; import './App.css'; import Myfunctionalcomp from "../src/components/Myfunctionalcomp"; import Myclassomp from "../src/components/Myclasscomp"; function App() { return ( <div> <h1>Hello, welcome to Appsloveworld</h1> <h1>React Js Tutorial</h1> <Myfunctionalcomp></Myfunctionalcomp><br></br> <Myclassomp></Myclassomp> </div> ); } export default App;
So let me compile it and check my browser.
- One unique feature of default export is that I can rename the file while I’m importing it.
import logo from './logo.svg'; import './App.css'; import Fncomp from "../src/components/Myfunctionalcomp"; import Myclassomp from "../src/components/Myclasscomp"; function App() { return ( <div> <h1>Hello, welcome to Appsloveworld</h1> <h1>React Js Tutorial</h1> <Fncomp></Fncomp><br></br> <Myclassomp></Myclassomp> </div> ); } export default App;
The next type of export is the named export or just export.
So named export can be used to export multiple objects, be it functions, class, etc.from a file. There can be several named exports from a single file.
- One hack is that while you’re importing, it cannot be re-named.
So let me show you how this works. so let’s create another class in our class component. so when I’m exporting it, I don’t want default.
import React, { Component } from "react"; export class Myclasscomp extends Component { render() { return <b>Hello this is class Component</b> } } export class MyclasscompSecond extends Component { render() { return <b>Hello this is second class Component</b> } }
In my app,js while importing it, I want to import both the classes.I Will include them within curly braces.
import logo from './logo.svg'; import './App.css'; import Fncomp from "../src/components/Myfunctionalcomp"; import {Myclasscomp,MyclasscompSecond} from "../src/components/Myclasscomp"; function App() { return ( <div> <h1>Hello, welcome to Appsloveworld</h1> <h1>React Js Tutorial</h1> <Fncomp></Fncomp><br></br> <Myclasscomp></Myclasscomp> <MyclasscompSecond></MyclasscompSecond> </div> ); } export default App;
So we have successfully exported both the classes from the class component and imported it back in our App.js component .
One advantage of using named export is the fact that I can choose to import the classes that I want to. say for example, I do not want to import MyclasscompSecond component we can remove it.
import {Myclasscomp} from “../src/components/Myclasscomp”;
- Higher-Order the components are basically functions that they taken a component and return a new component. The whole ideology behind higher component is to facilitate the reusability of component logic.
- Pure component optimize react code and also improves performance.
The post What is Components in React Js? appeared first on Software Development | Programming Tutorials.
Read More Articles
- What are React controlled components and uncontrolled components?
- What is the difference between arrow functions and regular functions inside React functional components (no longer using class components)?
- What is the simplest way to share react components between projects?
- What is the right way to import 3rd party React components into the kotlin.js project?
- What is the default implementation for "shouldComponentUpdate" lifecycle method in React components
- what is proper way to import multiple components from same file in react instead of getting each component imported
- What is best practice to communicate between React components and services?
- React Components - What is the proper way to create them?
- What is the best way to apply layout styling to styled-components and React components used in different places on a site?
- what is the equivalent of this.props.history.push('/some_route') of react class components in hooks?
- What is the most efficient way to toggle between two components React JS?
- What is the best way to include css files for Prime React components when using Parceljs?
- What is wrong with the React components Route?
- What is a good way to make a link between two React components at different hierarchy levels?
- What is the best way to test methods that traverse the react components
- What is the proper way to create reusable components react
- What is the easy and proper way of communicating components in React Hooks?
- What is the best way to delay re-render for controlled components in React JS?
- What should the React children type be for components that only accept text and falsy?
- What type to assign to children when they are all react components
- What components require state, understanding react
- What are these three dots in React doing?
- What is the difference between React Native and React?
- What is the difference between using constructor vs getInitialState in React / React Native?
- When to use ES6 class based React components vs. functional ES6 React components?
- How to access a DOM element in React? What is the equilvalent of document.getElementById() in React
- What is the best way to access redux store outside a react component?
- React native text going off my screen, refusing to wrap. What to do?
- React functional stateless component, PureComponent, Component; what are the differences and when should we use what?
- How can I prevent event bubbling in nested React components on click?
- TypeError: Cannot read property 'image' of undefined React state
- Page refreshes after the dropdown value is selected in React
- How to build programmatically the path for object data in React
- Replace reducer proper typing
- New event doesn't have latest state value updated by previous event
- How to comment HTML within React written in TypeScript?
- Warning while using Select component without any value
- Nesting in emotion using css
- Reactjs react router dom useParams not working with dynamic url
- babel wrongly transpiles export default function
- Next.js setting current active class with Link and router
- React/Webpack images not loading, but CSS does
- change date using useState reactjs
- React js onClick can't pass value to method
- How to implement real time collaboration in atlaskit editor?
- Updating property inside a nested array of object
- How to get Map object in react-leaflet on zoom change event
- How to make Puppeteer work with a ReactJS application on the client-side
- Styling svg in React with Sass
- Insert React JS-JSX inside J2EE application
- Custom React Hook with callback is making closure
- How to make a reat-mapbox-gl marker component draggable?
- file input files not read onChange on mobile
- basic React Gatsby project - can't push to GitHub - getting "git push --set-upstream origin master"
- Unable to dispatch an action in react-redux using typescript
- maxWidth uncenters dialog box (modal) for material-ui
- ReactJS with Webpack: Uncaught ReferenceError: require is not defined
- Mocking function on default export of hook
- How to get values from child components in React
- How to I fill a nested array with setState?
- Can't map over a query in React
- react js with redux, my container isn't receiving data after success actions / reducers
- React and SVG. Works for JSX, fails when used in Style
- redux-sagas generator yield failing inside callback
- Displaying a table using react components - Is this the right way to display a table?
- how to traverse json api data object
- DrawerNavigator: Change Text Color
- React js getInitialState not working after converting to es6
- Make Styles React JS
- Render Redux Form fields programmatically
- react-google-maps is refreshing the map when onclick is performed
- Undefined parameter used within function
- React function Component state - Too many re-renders. React limits the number of renders to prevent an infinite loop
- How to use setState function synchronously in zustand?
- How to render a d3.js map inside of a React component?
- javascript remove text with double inverted comma not working
- React Router props.history
- Leaflet React get map instance in functional component
- how to change referrer-policy in react js
- How to send error messages from express to react/redux
- explicit-function-return-type creating functional component react in typescript
- Module not found: Can't resolve './node_modules/@material-ui/core/IconButton'
- ReactJS: Events in .map(array) not fired
- useState not updating all components of my app
- why does all other values update while i used useEffect() on just 'time'?
- How do I edit multiple input controlled components in React?
- Is it possible to use Sass variable within styled-component @media query?
- arrow function inside parentheses {} about react context
- Passing through function to component, REACT
- React update component state from child component
- How to create a package with the isolatedModules=true option enabled?
- how to use two useState in one function so that the second useState can use the first updated useState?
- Facebook React: Uncaught Error: Invariant Violation: getDOMNode(): A component must be mounted to have a DOM node
- ReactJS ReactDOM Render for Separate Pages
- How to make a Soap call in React js?
- What is a good way to integrate formik with material-table?
- Rendering Child Component after Parent in React
- why my code calling API for multiple time instedof just once after delaying of 500 ms using debounce
- React PropTypes.array has keys with type string
- React Data Grid shows bad
- react-select not updating selected value on initial select
- How to import jsx with state variables into another react component?
- Show nested route component in new page
- Measure React DOM node on resize with hooks
- Change a single product quantity using state (react)
- Curiosity on react(?) or javascript syntax
- How can I add the 'All' checkbox in order to select all the other options?
- React Hooks(useEffect) form Sub mission
- Use object included from global <script> tag inside React component
- Exact same code from dangerouslySetInnerHTML not working only inside Gatsby / ReactJS page
- How to apply this functionality without refs and DOM manipulation
- How to get the label of dropdown in react?
- How is it possible to call confirm() before submitting a form in React?
- React Private Routes are not being redirected and they don't exist
- reactjs with axios “Cannot read property 'map' of undefined`”
- Why is React.memo not working with useEffect?
- Uncaught Error: "category" is not a registered scale
- Cannot get Signal R working due to cors issue - blocked by cors policy
- How to upload image as file in React with TypeScript
- How to get the value from the react fabric ui checkbox
- Debounce in functional component
- ReactJs with media queries
- Using React to restrict/allow resource based on client ip address
- Express overwrites react-router client side routes
- Call javascript function from ReactJS
- How to make just 1 row editable in material-table?
- React zodResolver put constraint date should be greater than now
- Setting default value to dropdown of antdesign
- Same route hiding component issue
- React Paginate, hide right pagination links after break and before next link
- What happens if state is updated multiple times?
- React and Three.js MTLLoader "material.onBeforeCompile is undefined"
- What is the correct way to use material-ui CSS?
- react-router-dom rendering new page over current page
- how to make animation for div in react using react-spring when hiding?
- How can i remove employees from the array that have endDate property higher than current selected month?
- click button to route to next page
- webpack-cli@3.0.8 requires a peer of webpack@^4.x.x but none is installed
- React : get Form values from children component on submit
- Using "material-components-web" within "react-boilerplate" code
- InvalidSignatureException from POST request
- Webpack-Dev-Server: Errors while compiling. Reload prevented. (Stack: React)
- shuffle function called every time state is updated?
- message sent but not received socket.on(...) for client
- Redirecting from getInitalProps in React/Next.js
- NextJS: Module not found: Can't resolve 'fs'
- React NPM inefficient regular expression complexity in nth-check
- Axios doenst send formData in put method
- How to embed an exact place on google maps in Reactjs
- Table with one row ignoring number of columns
- Framer Motion and React router 5: How do I prevent re-render of parent components with nested routes?
- Unexpected token React / JSON
- How to prevent variable from being reinitialized every render
- File upload with react, nodeJS multer doesn't work
- Axios is returning empty string value
- Iterating through JSON with Redux (how do I organise my reducers for this?)
- ReactJS Changing states from the child component
- Next.js read Firestore data
- Reactjs Uncontrolled component error in material ui radio button group
- How to optimize multiple variable check
- A component suspended while responding to synchronous input
- React mixing units error: Can't calculate vw and px together in css calc() function
- How to select the array item (array of objects) based upon a particular attribute
- Unexpected token = on first function in a class of React JS
- ReactJs how to hide load more option after all data fetch from database?
- Any easy way to import multiple image files at once in react
- Calc App React Undefined
- react-router with context - why doesn't it work the same with anchor vs Link
- Execute useQuery() hook when returning to previous screen react native stack navigator
- How can I save in state the response of an Api Call?
- How to disable AMD on 4 files and load them in order with webpack
- Unit Testing Redux Sagas
- Karma - Jquery: How to Get Client Side Jquery Code to Work in Karma Tests?
- React Builds- Which files go on the server? Why isn't my project deploying?
- React JS onClick event inside a tag
- Cannot access build on linux server
- How do make an interface for a state using generics which extend a certain object?
- Loading three.js texture in react as base64 string
- Refining code: Is there a better way to map one (shorter) array to another (longer) array of objects in Javascript?
- Set value to state React js
- JSX/JavaScript syntax in Chrome
- How onChange checkbox after checked based on index and selected 1 by 1
- React Native pass parameters through map function
- Difference between a function and a stateless component?
- Initial value for useState isn't updating when using Virtual Keyboard
- webpack for development mode
- React "useViewBox" hook for SVG viewBox failing ESLint rule exhaustive-deps
- Uppy DropTarget with React
- Display mongoDB data in a table with most recent date at the top of list in ReactJS
- How to convert CSV data to file type in Reactjs
- Receiving error when using setState within fetch to set response data and boolean value of state
- How to export data displayed in current page only in Ag-Grid?
- search data not displayed
- Adding swagger-UI with angular 10
- Link changing URL but not the page
- Trying to deploy my react app on Netlify which I created on a local host, but get an error while trying to deploy
- How to make a select input that is dependent on other inputs to always show a default value in React?
- How to command+click to open url in new tab and switch to it in JavaScript?
- React JS range slider - using an array for the value?
- Is it not correct to do api call without useEffect?