My React Journey: Day 23
December 21, 2024

My React Journey: Day 23



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

  1. Read-only: Child components cannot be modified.
  2. Used for functional and class components.
  3. PropTypes: Ensure props have the correct data type during development.
age: PropTypes.number; // Throws a warning if a non-number is passed.
Enter full screen mode

Exit full screen mode

4.DefaultProps: Provides default values ​​when no properties are passed.

name: "Guest"; // Default value for the name prop.
Enter full screen mode

Exit full screen mode

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, };
Enter full screen mode

Exit full screen mode

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

  1. Can only be used in class elements (in older React).
  2. Mutable: updated using this.setState().
  3. 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 */}
    >
  );
}
Enter full screen mode

Exit full screen mode

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(
  
    
  
);
Enter full screen mode

Exit full screen mode

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.

2024-12-21 21:46:58

Leave a Reply

Your email address will not be published. Required fields are marked *