0% found this document useful (0 votes)
6 views9 pages

React concepts

This document serves as a quick start guide to React, covering key concepts such as creating and nesting components, using JSX, adding styles, and managing state with hooks. It explains how to display data, conditionally render components, respond to events, and share state between components. The guide concludes with next steps for building a small React app using the learned concepts.

Uploaded by

Anusree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views9 pages

React concepts

This document serves as a quick start guide to React, covering key concepts such as creating and nesting components, using JSX, adding styles, and managing state with hooks. It explains how to display data, conditionally render components, respond to events, and share state between components. The guide concludes with next steps for building a small React app using the learned concepts.

Uploaded by

Anusree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

Table of Contents

Table of Contents................................................................................................................... 1
React Quick Start - Key Concepts:.......................................................................................1
Creating and Nesting Components:..................................................................................... 1
Writing Markup with JSX:...................................................................................................... 2
Adding Styles:........................................................................................................................ 2
Displaying Data:..................................................................................................................... 3
Conditional Rendering:......................................................................................................... 3
Rendering Lists:..................................................................................................................... 4
Responding to Events:.......................................................................................................... 5
Updating the Screen:............................................................................................................. 5
Using Hooks:.......................................................................................................................... 6
Sharing Data Between Components.................................................................................... 7
Scenario 1: Independent Component State....................................................................... 7
Diagram:....................................................................................................................... 7
Scenario 2: Shared State................................................................................................... 7
Diagram:....................................................................................................................... 8
Code Example:...................................................................................................................8
Key Concepts:.................................................................................................................... 9
Next Steps...............................................................................................................................9

React Quick Start - Key Concepts:

●​ Create and nest components.


●​ Add markup and styles.
●​ Display data.
●​ Render conditions and lists.
●​ Respond to events and update the screen.
●​ Share data between components.

Creating and Nesting Components:

●​ React apps are built from components.


●​ A component represents a part of the UI, with its own logic and appearance.
●​ Components can range from small (e.g., button) to large (e.g., entire page).
●​ React components are JavaScript functions returning markup.

function MyButton() {​
return (​
<button>I'm a button</button>​
);​
}

●​ Components can be nested into other components.


export default function MyApp() {​
return (​
<div>​
<h1>Welcome to my app</h1>​
<MyButton />​
</div>​
);​
}

●​ Component names must start with a capital letter (e.g., <MyButton />).
●​ HTML tags must remain lowercase (e.g., <div> or <button>).
●​ Use export default for the main component in a file.
●​ For JavaScript syntax references, check MDN or javascript.info.

Writing Markup with JSX:

●​ JSX is a syntax extension for writing markup in React (commonly used in React
projects).
●​ Supported out of the box by recommended React development tools.
●​ Stricter than HTML:
○​ Tags must always be closed (e.g., <br />).
○​ Components must return a single parent element, like a <div> or <>...</>
(fragment wrapper).

function AboutPage() {​
return (​
<>​
<h1>About</h1>​
<p>Hello there.<br />How do you do?</p>​
</>​
);​
}

●​ Use an online converter to easily port large amounts of HTML to JSX.

Adding Styles:

●​ Use className in React instead of class in HTML.

<img className="avatar" />

●​ Write CSS rules in a separate CSS file:


/* Example CSS */​
.avatar {​
border-radius: 50%;​
}

●​ React does not enforce a specific method for adding CSS.


●​ Simplest approach: add a <link> tag to your HTML for the CSS file.
●​ For build tools or frameworks, refer to their respective documentation for adding
CSS.

Displaying Data:

●​ JSX allows embedding JavaScript variables into markup using curly braces {}.
●​ For example, {user.name} displays the value of user.name.

<h1>{user.name}</h1>

●​ You can use curly braces in JSX attributes to pass JavaScript values (not just
strings).
●​ For example, src={user.imageUrl} uses the value of user.imageUrl for the
src attribute.

<img className="avatar" src={user.imageUrl} />

●​ Complex expressions can also be used inside JSX curly braces (e.g., string
concatenation).

alt={'Photo of ' + user.name}

●​ The style attribute uses a regular JavaScript object inside curly braces to apply
styles dynamically.

style={{ width: user.imageSize, height: user.imageSize }}

Conditional Rendering:

●​ React uses standard JavaScript techniques for conditions (no special syntax).
●​ Use an if statement to conditionally include JSX.
let content;​
if (isLoggedIn) {​
content = <AdminPanel />;​
} else {​
content = <LoginForm />;​
}​
return <div>{content}</div>;

●​ Use the conditional ? operator for more compact code inside JSX.

<div>​
{isLoggedIn ? <AdminPanel /> : <LoginForm />}​
</div>

●​ Use logical && for conditions without an else branch.

<div>​
{isLoggedIn && <AdminPanel />}​
</div>

●​ These techniques also work for conditionally setting attributes.


●​ If unfamiliar with these syntaxes, start by using if...else.

Rendering Lists:

●​ Use JavaScript features like for loops and map() to render lists of components.
●​ Example: an array of products:

const products = [​
{ title: 'Cabbage', id: 1 },​
{ title: 'Garlic', id: 2 },​
{ title: 'Apple', id: 3 },​
];

●​ Use map() to transform the array into a list of <li> items.

const listItems = products.map(product =>​


<li key={product.id}>​
{product.title}​
</li>​
);

●​ Return the list inside an unordered list (<ul>).

return <ul>{listItems}</ul>;

●​ Each list item (<li>) must have a key attribute to uniquely identify it.​

●​ The key usually comes from the data (e.g., database ID).​

●​ React uses key to track changes when inserting, deleting, or reordering items.​

●​ Example with conditional styling:​

<li​
key={product.id}​
style={{ color: product.isFruit ? 'magenta' : 'darkgreen' }}​
>​
{product.title}​
</li>

Responding to Events:

●​ Declare event handler functions inside components.

function handleClick() {​
alert('You clicked me!');​
}

●​ Attach event handlers using JSX attributes (e.g., onClick={handleClick}).

<button onClick={handleClick}>Click me</button>

●​ Do not add parentheses to the event handler (e.g., onClick={handleClick()} is


wrong).
●​ React will call the event handler when the event occurs.

Updating the Screen:


●​ To track and display information, add state to components.
●​ Import useState from React.

import { useState } from 'react';

●​ Declare a state variable inside the component.

const [count, setCount] = useState(0);

●​ useState returns two values: current state (count) and the function to update it
(setCount).
●​ Convention: [stateVariable, setStateFunction].
●​ Pass initial value to useState (e.g., 0 for count).

const [count, setCount] = useState(0);

●​ Call the update function (setCount()) to change state (e.g., setCount(count +


1)).

function handleClick() {​
setCount(count + 1);​
}

●​ React re-renders the component with updated state on each click.


●​ Each instance of the component maintains its own state.​

<MyButton />​
<MyButton />

●​ Clicking one button doesn’t affect others; each button remembers its own count.

Using Hooks:

●​ Functions starting with use are called Hooks (e.g., useState).


●​ useState is a built-in Hook provided by React.
●​ Other built-in Hooks are available in the React API reference.
●​ You can create custom Hooks by combining existing ones.
●​ Hooks have restrictions:
○​ Call Hooks only at the top level of components or other Hooks.
○​ Avoid calling Hooks inside conditions or loops; create a new component
instead.

Sharing Data Between Components

Scenario 1: Independent Component State

●​ Each MyButton has its own independent state (count).


●​ Clicking a button updates only that button’s count.

Diagram:

MyApp​
└── MyButton (count: 0)​
└── MyButton (count: 0)

●​ Initial: Each MyButton has count = 0.


●​ After Click: Only the clicked button updates its count.

Scenario 2: Shared State

●​ Move state “upwards” to the closest common parent (MyApp).


●​ Shared state is passed down to child components (MyButton).
●​ Both buttons update together when the state in MyApp changes.
Diagram:

MyApp (count: 0)​


└── MyButton (count: 0)​
└── MyButton (count: 0)

●​ Initial: MyApp has count = 0; passed down to MyButton.


●​ After Click: MyApp updates count to 1; both MyButton update their count.

Code Example:

●​ Move state to parent MyApp.

export default function MyApp() {​


const [count, setCount] = useState(0);​

function handleClick() {​
setCount(count + 1);​
}​

return (​
<div>​
<h1>Counters that update together</h1>​
<MyButton count={count} onClick={handleClick} />​
<MyButton count={count} onClick={handleClick} />​
</div>​
);​
}

●​ Pass state as props to MyButton.

function MyButton({ count, onClick }) {​


return (​
<button onClick={onClick}>​
Clicked {count} times​
</button>​
);​
}

●​ Props: count and onClick are passed down to MyButton.

Key Concepts:

●​ Lifting state up: Move state to the parent and pass it down as props.
●​ Props: Data passed from parent to child components (e.g., count, onClick).

Next Steps

●​ Basics Learned: Components, JSX, Hooks, State, Events, Props.


●​ Next Goal: Build a small React app using these concepts.

You might also like