props and status
Props
Props, abbreviation characteristicyes read-only
and immutable data
Passed from parent component to child component. They are mainly used to transfer data between components and ensure reusability.
Main features of props
- Read-only: Child components cannot be modified.
- Used for functional and class components.
- PropTypes: Ensure props have the correct data type during development.
age: PropTypes.number; // Throws a warning if a non-number is passed.
4.DefaultProps: Provides default values when no properties are passed.
name: "Guest"; // Default value for the name prop.
Code example
student.jsx
import PropTypes from 'prop-types';
export default function Student(props) {
return (
Name: {props.name}
Age: {props.age}
Student: {props.isStudent ? 'Yes' : 'No'}
);
}
// PropTypes
Student.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
isStudent: PropTypes.bool,
};
// DefaultProps
Student.defaultProps = {
name: 'Guest',
age: 0,
isStudent: false,
};
state
A state is an object within a component that holds dynamic values that can change over time. States are mutable and are typically used for user interactions and events.
Main characteristics of the country
- Can only be used in class elements (in older React).
- Mutable: updated using this.setState().
- Track dynamic data, such as user input or live responses.
App.jsx implementation
Props are passed from the App component to the Student component.
application.jsx
import React from 'react';
import Student from './Student';
export default function App() {
return (
<>
{/* Uses defaultProps */}
{/* Partial DefaultProps */}
>
);
}
Rendering in the DOM
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
createRoot(document.getElementById('root')).render(
);
focus
- Props: Immutable, passed from parent to child, and intended for reuse.
- State: Mutable, manages dynamic behavior and updates using this.setState().
- In modern React, hooks like useState enable function elements to also manage state, eliminating the need for class elements.