본문 바로가기
개념/React

React) isRequired

by kiseno 2025. 4. 10.
728x90
반응형
SMALL
//App.js

//import Mycomponent from "./mycomponent";
//
// const App =()=>{
//     return <Mycomponent name = "React" favoriteNumber={1}>react</Mycomponent>;
// };
//
// export default App;

import propTypes from "prop-types";

const mycomponent = ({name, favoriteNumber, children}) =>{
    return(
        <div>
            hello, my name is {name}<br/>
            children value is {children}<br/>
            my favorite number is {favoriteNumber}
        </div>
    );
};

mycomponent.defaultProps = {
    name : 'basic name'
};
mycomponent.propTypes ={
    name : propTypes.string,
    favoriteNumber : propTypes.number.isRequired
};

export default mycomponent;

### Functional Component Definition

- The component is defined as a functional component, which is a simpler and more concise way to create components in React compared to class components. It takes props as an argument and returns JSX.

### Props and Destructuring

- The function's parameters use destructuring to directly extract `name`, `favoriteNumber`, and `children` from the props object. This approach allows for a cleaner and more readable component.

### Default Props

- `defaultProps` is set on `mycomponent` to provide a default value for the `name` prop. This means if the `name` prop is not specified by the parent component, "basic name" will be used as a fallback.

### PropTypes

- `propTypes` is assigned to `mycomponent` to enforce type checking for the props. It ensures `name` is a string and `favoriteNumber` is a number. Moreover, `favoriteNumber` is marked as `isRequired`, meaning the component will validate that `favoriteNumber` is provided and is of the correct type, helping to catch bugs and ensure component usage correctness.

### Rendering JSX

- The component returns JSX that constructs a `div` with a greeting message incorporating the `name`, `children`, and `favoriteNumber` values. This demonstrates how props can be used within the component to dynamically render content.

### Integration with an App Component

- The commented `App.js` code shows how `mycomponent` is intended to be used within a larger application. It demonstrates passing the `name` prop with the value "React", the `favoriteNumber` prop with the value `1`, and the children between the opening and closing tags of `mycomponent`.

### Exporting the Component

- `export default mycomponent;` makes the component available for import and use in other parts of the application, such as the `App` component shown in the comment.

728x90
반응형
LIST

'개념 > React' 카테고리의 다른 글

React) class_component_state  (0) 2025.04.12
React) class_component_props  (0) 2025.04.11
React) multiple state value  (0) 2025.04.09
React) mycomponent  (0) 2025.04.08
React) mycomponent props children  (0) 2025.04.07