[go: up one dir, main page]

0% found this document useful (0 votes)
8 views8 pages

Webii React Basics (Components, Props)Lesson005

This document provides an overview of React components, detailing their structure, types (functional and class components), and how to create and use them within a React application. It emphasizes the importance of props for passing data between components and best practices for component design. Additionally, it includes examples of component creation and usage, along with key concepts related to props.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Webii React Basics (Components, Props)Lesson005

This document provides an overview of React components, detailing their structure, types (functional and class components), and how to create and use them within a React application. It emphasizes the importance of props for passing data between components and best practices for component design. Additionally, it includes examples of component creation and usage, along with key concepts related to props.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

REACT COMPONENTS

Use these procedures to install react

npm create vite@latest web-ii -- --template react

cd web-ii

npm install

npm run dev

In React, React components are independent, reusable building blocks in a React application
that define what gets displayed on the UI. They accept inputs called props and return React
elements describing the UI.

What Are React Components?

A component is a building block that encapsulates a piece of the user interface (UI). It defines
the structure and behavior of the UI, either by managing its own state or by receiving data
through props and rendering content accordingly. Components are reusable and can be
composed together to build complex UIs in a modular way.

 Components can be reused across different parts of the application to maintain


consistency and reduce code duplication.

 Components manage how their output is rendered in the DOM based on their state and
props.

 React loads only the necessary components, ensuring optimized performance.

 Only the specific Component updates instead of the whole page.

A component is like a small building block.


You can imagine your website like a house and each room (kitchen, bedroom, bathroom) is a
component.
In React, you build small components, and then combine them to make your whole app.

Types of React Components

There are two primary types of React components:


1. Functional Components. they are simpler and preferred for most use cases. They
are JavaScript functions that return React elements. With the introduction of React Hooks,
functional components can also manage state and lifecycle events.

 Stateless or Stateful: Can manage state using React Hooks.

 Simpler Syntax: Ideal for small and reusable components.

 Performance: Generally faster since they don’t require a ‘this’ keyword.

function Greet(props) {

return <h1>Hello, {props.name}!</h1>;

2. Class Components

Class components are ES6 classes that extend React.Component. They include additional
features like state management and lifecycle methods.

 State Management: State is managed using the this.state property.

 Lifecycle Methods: Includes methods like componentDidMount, componentDidUpdate,


etc.

class Greet extends React.Component {

render() {

return <h1>Hello, {this.props.name}!</h1>;

How to create a simple React component?

There are two main ways:

1. Function Components it is most common and easy to use

2. Class Components it is older style less used today


Function Component Example

MyComponent.jsx

import React from 'react';

function MyComponent() {

return (

<div>

<h1>Hello, I am a React Component!</h1>

<p>This component was imported into App.jsx</p>

</div>

);

export default MyComponent;

Explanation:

There is a function MyComponent() {} which is a normal JavaScript function.

It returns some HTML looking code (this is called JSX).

Then it exports default MyComponent; This allows you to use it in other files.

How to use a component inside another component?

Let’s say you have MyComponent.jsx, and you want to use it inside your App.jsx (main file).

import MyComponent from './Component/MyComponent'; // import the component

import Greeting from './Component/Greeting';

import './index.css';

function App() {
return (

<div className="app">

<h1>Welcome to My App</h1>

<MyComponent /> {/* use the component like a HTML tag */}

{/* Props Demonstration */}

<Greeting name="Alice" color="blue" />

<Greeting name="Bob" color="green" />

<Greeting /> {/* Shows default values */}

</div>

);

export default App;

Explanation:

You import the component first.

You use it like a normal HTML tag: <MyComponent />.

main.jsx

import React from 'react';

import ReactDOM from 'react-dom/client';

import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(

<React.StrictMode>

<App />
</React.StrictMode>

);

Props in React Components

Props (short for properties) are read-only inputs passed from a parent component to a child
component. They enable dynamic data flow and reusability.

Props are immutable.

They enable communication between components.

Child Component (Greeting.jsx) - Receives Props

function Greeting(props) {

return (

<h2 style={{ color: props.color || 'black' }}>

Hello, {props.name || 'Stranger'}!

</h2>

);

export default Greeting;

Explanation

props is an object containing all the attributes passed to the component.

props.name and props.color are accessed to customize the output.

Default values (|| 'Stranger') ensure the component works even if props are missing.

Parent Component (App.jsx) - Passes Props

import MyComponent from './Component/MyComponent';

import Greeting from './Component/Greeting';


import './index.css';

function App() {

return (

<div className="app">

<h1>Welcome to My App</h1>

<MyComponent />

{/* Props Demonstration */}

<Greeting name="Alice" color="blue" />

<Greeting name="Bob" color="green" />

<Greeting /> {/* Shows default values */}

</div>

);

export default App;

explaination

<Greeting name="Alice" color="blue" />


props = { name: "Alice", color: "blue" }
→ Renders: "Hello, Alice!" in blue.

<Greeting name="Bob" color="green" />


→ props = { name: "Bob", color: "green" }
→ Renders: "Hello, Bob!" in green.

<Greeting /> (no props passed)


→ props = {}
→ Falls back to defaults: "Hello, Stranger!" in black.
Key Concepts About Props

1. Props Are Immutable (Read-Only)

The child component cannot modify props.

Example: If you try to do props.name = "Charlie", React will give an error.

2. Props Can Be Any JavaScript Value

 Strings: <Greeting name="Alice" />

 Numbers: <Counter initialValue={5} />

 Booleans: <UserProfile isLoggedIn={true} />

 Objects: <User data={{ name: "Alice", age: 25 }} />

 Functions: <Button onClick={() => alert("Clicked!")} />

3. Destructuring Props (Cleaner Syntax)

Instead of props.name, you can destructure props for better readability:

function Greeting({ name, color }) {

return <h2 style={{ color }}>Hello, {name}!</h2>;

 Now, you use name and color directly instead of props.name.

4. Default Props (Alternative to ||)

You can define default values explicitly:

function Greeting({ name = "Stranger", color = "black" }) {

return <h2 style={{ color }}>Hello, {name}!</h2>;

 If name is not provided, it defaults to "Stranger".

When to Use Props?

Passing static data (e.g., user name, theme color)


Parent-to-child communication
Making reusable components (e.g., buttons, cards)
Avoid using props for:

 Data that changes over time (use state instead).

 Complex nested data (consider context or state management).

Best Practices for React Components

 Keep Components Small: Each component should do one thing well.

 Use Functional Components: Unless lifecycle methods or error boundaries are required.

 Prop Validation: Use PropTypes to enforce correct prop types.

 State Management: Lift state to the nearest common ancestor when multiple
components need access.

You might also like