Lesson 05 Creating Reusable component
3 min read
1 year ago
Published on Apr 28, 2024
This response is partially generated with the help of AI. It may contain inaccuracies.
Table of Contents
Step-by-Step Tutorial: Creating a Reusable Component
-
Create a Section Component:
- Create a section component with a title, switch, and a list of movies.
- Inside your folder, create a new file called
Section.js
. - Define and export a default functional component named
Section
. - Set the width of the section to 240 pixels and the height of the switch to 30 pixels.
-
Structure the Section Component:
- Add a header to the section component.
- Pass the title as a prop to the section component.
- Style the title with semi-bold font and 2x text size.
-
Create the Switch Component:
- Create a switch component inside the
Switch.js
file. - Export the switch component as the default export.
- Create a switch component inside the
-
Add Items to the Switch Component:
- Define an array of items for the switch component, such as "In Theaters."
- Pass the items array to the switch component.
-
Style the Switch Component:
- Apply styling to the switch component, such as setting the border color to dark blue and the height to 30 pixels.
- Use Flexbox to align the items in the switch component.
-
Add Interactivity to the Switch Component:
- Implement a toggle functionality using the state hook.
- Create a function to handle the toggle state changes.
- Update the switch component's style based on the toggle state (active or inactive).
-
Implement Dynamic Width Calculation:
- Use the
useRef
hook to access the DOM elements' width. - Calculate and set the width dynamically for the switch items based on their content.
- Use the
-
Pass Data from Child to Parent Component:
- Define a function in the parent component to receive data from the child (switch component).
- Pass the function as a prop to the switch component.
- Call the function in the switch component with the selected value.
-
Update Parent Component State:
- Create a state in the parent component to store the selected value.
- Update the parent component state with the selected value received from the switch component.
-
Finalize and Test:
- Ensure that the switch component updates the parent component state correctly.
- Test the switch component's functionality, including toggling and dynamic width calculation.
- Refactor and optimize the code as needed.
Congratulations! You have successfully created a reusable component with interactive functionality in React. Feel free to further enhance the component and explore more React features in your projects.