Maximizing the versatility of components with styled-components and React: A comprehensive guide to incorporating variants

Currently, I am a novice programmer working on a personal project using React for the front-end. I am looking to create a Button component with the styled-components package that can be easily reused throughout the app with some variations in size, color, and hover effects. The Button will be used in various sections like individual posts, navigation bars, and forms. However, as I have only implemented it in a few instances so far, the code for the component is becoming quite complex to manage. Here is how it looks currently:

import styled from 'styled-components';
import { Link } from 'react-router-dom';

const Button = styled(Link)`
  margin: 5px;
  display: grid;
  place-items: center;
  font-size: 1em;
  padding: 0 1em;
  height: ${props => (props.small ? '35px' : '40px')};
  background: ${props => (props.nav ? props.theme.color.white : '#30336b1a')};
  border-radius: ${props => (props.small ? '3px' : '5px')};
  color: ${props => (props.nav ? props.theme.color.forest : '#30336b')};
  border: ${props =>
    props.outline ? `2px solid ${props.theme.color.forest}` : null};
  text-decoration: none;
  transition: 0.2s ease-in-out;

  &:hover {
    background: ${props => (props.nav ? props.theme.color.forest : '#f6e58d')};
    color: ${props => (props.nav ? props.theme.color.white : null)};
  }
`;

export default Button;

The current variants are named small, nav, and outline. I feel the need to introduce more variants but the syntax

props=> props.variant? do-this: or-that;
is starting to become cumbersome and difficult to read.

I am contemplating either extending the component and creating multiple ButtonVariant components or using if-else or switch statements to return different styled variants. Both methods aim to avoid repeating code by utilizing them with styled(Button). Yet, I seek advice from experienced individuals on what would be better in terms of performance and maintainability within the codebase. Despite thorough documentation and extensive research online, I have yet to find a definitive answer.

Answer №1

To create a function that returns a value, you can define it outside of your main code block. You can then use conditional statements like if or switch() to check different cases:

const setButtonSize = (size) => {
    switch(size){
       case 'sm':
         return '30px';
       case 'md':
         return '35px';
       //--------------You can add more size options here and their corresponding values
       default:
         return '40px';
    }
};


const StyledButton = styled(Link)`
  height: ${props => setButtonSize(props.size)};
`;

This is just a basic concept that may be applicable in your scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortless floating made possible by the magic of Twitter Bootstrap

I am currently working with a group of elements that are designated as row-fluid and span12, each containing span4 elements. My goal is to have these elements automatically align in columns of 3, regardless of how many are present. However, I am facing an ...

Using JavaScript functions within a WebView and ViewPager

Encountering an issue with Javascript in WebView. I have a ViewPager that dynamically adds Views as needed. Prior to adding a View to the viewpager, I inflate it and load an embedded webview inside: LayoutInflater inflater = this.getLayoutInflater(); ...

Difficulty arises when a function in ReactJS returns an empty object

I'm currently working on a project that involves allowing users to click on Travel Tour "Cards" and be redirected to a new page where all the details related to that specific card are displayed! However, I've encountered an issue with this parti ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

What is the best way to transfer user data from the backend to the frontend?

I successfully created a replica of YelpCamp using Node and EJS, but now I am attempting to convert it into a Node-React project. Everything was going smoothly until I encountered an issue while trying to list a specific user in the SHOW route. In order to ...

Loop through items in Node.js

Is anyone familiar with a way to obtain the computed styles of anchor tags when hovering over them on a webpage? I've tried using this function, but it only returns the original styles of the anchor and not the hover styles. Any assistance would be gr ...

Authentication using tokens - JSON Web Tokens

While working with jsonwebtoken in Node, we generate a unique token for each user and return it to them. But when the user sends this token in the authentication header (Authentication: <token>), how does jwt differentiate between tokens from diffe ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

Images fail to load on a NodeJS server running on localhost

Whenever I attempt to set up a NodeJs server and run it with an HTML file, the images are not loading properly. Here is the NodeJS code snippet: var http = require('http'); var fs = require('fs'); fs.readFile('main.html', fu ...

Determine the exact width of text without rounding in Javascript

I'm facing an issue with a div element that I'm manipulating using Javascript to change its position. The problem is that it's rounding off incorrectly. #hi{ background-color: blue; width: 2px; height: 10px; position: absolu ...

Tips for getting rid of NavLink styling when Routes are not selected

I need assistance in restoring the default style of NavLink as shown in the screenshot below. The color should be white and without underlines. Here is my code snippet: Home is currently selected as the default path, and the activeClass property is functio ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Ensure that the script continues to run uninterrupted even after the user has navigated away from the

Currently, I am working on an application that allows users to purchase tickets for events using technologies such as node.js, express.js, sequelize, and react. After the user completes the ticket purchasing process, they are redirected to a page indicati ...

Customizing the font color and size of the brand text in the Bootstrap 5.1.3 Navigation Bar is not allowed

I am currently working on a main page that includes a bootstrap navigation bar with a dropdown menu. I have successfully managed to display the dropdown menu and change its color using CSS. However, I encountered an issue when attempting to modify the font ...

What is the best method for transferring formatted text from the clipboard to an HTML textarea?

When you copy and paste from a web browser to a text processor, the HTML markup gets converted to rich text. The text processor then tries to convert this markup into its own format, proving that the Clipboard can hold markup. However, when you copy and p ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

Searching through an array of objects in MongoDB can be accomplished by using the appropriate query

Consider the MongoDB collection 'users' with the following document: { _id: 1, name: { first: 'John', last: 'Backus' }, birth: new Date('Dec 03, 1924'), death: new Date('Mar 1 ...

Can the Flash Configurator be converted to PHP or Javascript?

Considering converting this flash application into either PHP or JavaScript. Take a look at the example: In PHP, the page reloads every time the customer selects a color. With AJAX, it's challenging to pass the selected value to PHP. Are there any ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

Customize the layout of menu icon in HTML/CSS using FlexBox Grid

Recently, I have encountered an issue with the position of a menu icon on my website. The icon is displayed when the window reaches a certain size, but it is not aligned properly on the right side of the site. Ideally, I would like to use the "right" prope ...