The beginner's guide to creating react component
React components are reusable code that renders html which can be used in several places in your project. following is an example of the function component.
Props
The component may need some data, properties or input value which can be passed from where the component is declared. For example, I have a component called Count. Now it needs the property count to show the count in the component. Now in this case i need to pass the count as a prop to that component and that's how we can use the props. Here’s the implementation.
the prop argument in the component "Count" is nothing but the JSON so if you are using advance JavaScript you can also implement it in the following way.
Enhancing Reusability with Variants
Variants allows us to apply different styles to the same component based on the prop value. This approach offers flexibility and reusability, reducing the need to create multiple components for different styles. Following is the sample component which uses this approach to create differently sized text in one component.
Explaination of the logic:
Variants is the JSON object that maps variants to the CSS classes. Each key in the object represents a variant name, and the corresponding value is a string of CSS classes. The variant Prop is used to determine which classes to apply.
${(variants[variant] || "")}: This expression retrieves the value from the variants object using the variant prop. If the prop value does not match any key in the variants object, it defaults to an empty string, ensuring no additional classes are applied.
How to Use the Text Component:
Following is the output:
Heading
Heading 2
Paragraph
As you can see, by simply changing the "variant" prop, we can achieve different text sizes using the same `Text` component. This promotes code reusability and simplifies styling for various text elements in your React application.
Enhancing React Components with Libraries
To minimize your code for styling you can leverage popular libraries like tailwindCSS and bootstrap which provide you with predefined CSS classes.
- Uploaded by Tanay kulkarni
Date: 3rd July 2024