Webii React Basics (Components, Props)Lesson005
Webii React Basics (Components, Props)Lesson005
cd web-ii
npm install
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.
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 manage how their output is rendered in the DOM based on their state and
props.
function Greet(props) {
2. Class Components
Class components are ES6 classes that extend React.Component. They include additional
features like state management and lifecycle methods.
render() {
MyComponent.jsx
function MyComponent() {
return (
<div>
</div>
);
Explanation:
Then it exports default MyComponent; This allows you to use it in other files.
Let’s say you have MyComponent.jsx, and you want to use it inside your App.jsx (main file).
import './index.css';
function App() {
return (
<div className="app">
<h1>Welcome to My App</h1>
<MyComponent /> {/* use the component like a HTML tag */}
</div>
);
Explanation:
main.jsx
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Props (short for properties) are read-only inputs passed from a parent component to a child
component. They enable dynamic data flow and reusability.
function Greeting(props) {
return (
</h2>
);
Explanation
Default values (|| 'Stranger') ensure the component works even if props are missing.
function App() {
return (
<div className="app">
<h1>Welcome to My App</h1>
<MyComponent />
</div>
);
explaination
Use Functional Components: Unless lifecycle methods or error boundaries are required.
State Management: Lift state to the nearest common ancestor when multiple
components need access.