
React Function Component
Components are independent and reusable bits of code. They work same as JavaScript functions, but work in isolation and return HTML.Components are of two types, Class components and Function components, in this Blog we will concentrate on Function components.
What are Function Component
Functional components are the most common components that we will be working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function.
//Example for Function Component import React from "react" function Basic(){ return( <h1>welcome</h1> ) } export default Basic
React application consist of a component called App, which returns an <h2>
element.
//App componentfunction App() { return <h2>welcome to Diatoz</h2>; }
export default App
//Here we display the App component in the root elementconst root = ReactDOM.createRoot(document.getElementById('root')); root.render(
<App />
);
Function is a valid React component because it accepts a single "props"(properties)object argument with data and returns a React element. We call such components Function Components because they are literally JavaScript Function
//Example for Function Props import React from "react" function FirstName(props){ return <h1>welcome to,{props.name}</h1> } export default FirstName //Index.jsconst root = ReactDOM.createRoot(document.getElementById('root')); const element = <FirstName name=" Diatoz" />;
root.render(element);
React calls the Welcome
component with {name: 'Diatoz'}
as the props.
Our <Welcome>
component returns a <h1>Welcome to, Diatoz</h1>
element as the result.
Composing Components
Components refer to other components in their output. This lets us use the same component abstraction for any level of detailing. button, form, dialog, screen in React apps, this are expressed as components.
For example, we can create an App
component that renders WelcomePage many times:
// WelcomePage Component function WelcomePage(props){ return<h1>Welcome to,{props.name}</h1> } export default WelcomePage
// App Component
function App(){
return(
<div>
<WelcomePage name="Diatoz"/>
<WelcomePage name="e2eHiring"/>
</div>
);
}
export default App