Utilize React Styled Components to seamlessly unify the styles of two different components

I want to have consistent styles for both a styled input element and a styled select element.

Currently, I accomplish this using string interpolation:

const styles = `
    background-color: white;
    width: 100%;
    border: 0 solid transparent;
    border-radius: 10px;
    margin-bottom: 20px;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 1.2rem;
`

const Select = styled.select`${styles}`
const Input = styled.input`${styles}`

Is there a more efficient way to achieve this without relying on a 'raw' string? One drawback of using the raw styles string is that Visual Studio Code doesn't provide syntax highlighting for it:

https://i.sstatic.net/4cNJl.png

Answer №1

If you're looking for solutions, you have a few different options to consider:

Utilize the css helper function:

const styles = css`
  background-color: white;
  // ...
`;

const Select = styled.select`${styles}`;
const Input = styled.input`${styles}`;

Use the "as" polymorphic prop (introduced in version 4):

<Select as="input">
  ...
</Select>

Try the withComponent method (although it may be deprecated):

const Select = styled.select`
  background-color: white;
  // ...
`;
const Input = Select.withComponent('input');

Answer №2

If you want to include CSS using the css tagged template literal, you can follow this example:

import styled, { css } from "styled-components";

const styles = css`
  background-color: white;
  width: 100%;
`;

const Button = styled.button`${styles}`;
const Link = styled.a`${styles}`;

It should display properly with syntax highlighting (but I haven't tested it myself).

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

Modifying webpage design using JavaScript for styling

Is there a way to change the css style(defined in the page source) dynamically with Java? I know it is possible to do it with JavaScript. If there isn't, are there other situations where JavaScript is the only choice developing a web app? ...

Ways to expand HTML input fields to fill the whole table cell

Currently working on a calculator project and I'm facing an issue with making a HTML button span the entire cell. I've managed to stretch the button horizontally but struggling to get it to fill the cell completely. Curious as to why setting widt ...

When hovering over a div, reveal another div on top of a third div

Imagine two adjacent divs, A on the left and B on the right with some other elements in between. Is it possible to have a third div, C, appear over div A when hovering over div B? I can control the display property using CSS, but I am unsure how to make d ...

Display an error message in the input type file Form Control if the file format is not .doc or .docx

I need a way to display an alert if the user tries to submit a file that is not of type doc or docx. I've implemented a validator for this purpose and would like the alert message (Unacceptable file type) to be shown when the validation fails. Here i ...

What is the best way to place a vertical line above the text when it is in use?

How can I add a vertical line above the active element using CSS? I was recommended to use either :before or :after, but I'm not sure how to implement them. I tried using :after without success. Any advice on achieving this effect? See the design exam ...

Is it possible for me to create a Pomodoro clock similar to this one?

Can you provide guidance on creating a Pomodoro clock similar to this design: https://i.sstatic.net/qhd1Z.png As time progresses, the arrow should move around causing the circumference of the circle to increase. What approach or library would you recomm ...

The implementation of TypeScript 3.5 resulted in a malfunction where the imported namespace was unable to locate the Enum during runtime

I recently upgraded an older Angular.js application from Typescript 2.7 to 3.5 and successfully compiled it using tsc.exe. During application runtime, I encountered an error message in certain parts of the code: TypeError: Cannot read property 'Enu ...

Implement a new functionality to a publicly accessible type without violating the pre-established agreement

I'm looking to enhance an existing exported type with a new method, without causing any disruption to the current usage in production. import * as BunyanLogger from 'bunyan'; import init from './logger'; export type Logger = Bunya ...

Why do callbacks in Typescript fail to compile when their arguments don't match?

In my current project, I encountered a scenario where a React callback led to a contrived example. interface A { a: string b: string } interface B { a: string b: string c: string } function foo(fn: (a: A) => void, a: A) { fn( ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

The browser does not automatically set the Cookie

Trying to login involves making an API call using a POST HTTP request. post( postLogin(email), JSON.stringify({password: passwd}), { headers: { "Content-Type":"application/json" }, credentials: 'include' // also attempted with &a ...

Customize the background image in your Windows 8 app developed with HTML

While working on my app with the grid app template, I placed an image in the images folder. However, when I attempted to change the background image, it didn't seem to take effect. This is the code snippet that I used: HMTL <div id="contenthost" ...

What is the best way to dynamically include various properties in an object type depending on a generic union?

Consider the following union type: type Union = "a" | "b"; Is there a way to add multiple new keys to an object type with conditions? Adding one key with a condition is straightforward: type Condition<T extends Union> = { [K in ...

Use an observable stream instead of nesting promise.all to aggregate data from an array

In our Angular application, we have a method that combines the results of 3 APIs into a single list. loadPlaces$ = this.actions$.pipe( ofType(PlaceActionTypes.LOAD_PLACES), switchMap((action: LoadPlaces) => from(this.service.findAreas()). ...

Responsive Line Breaks in Bootstrap 4

I can't seem to find any information in the documentation to guide me in the right direction here. I'm hesitant to use columns as it could result in gaps between the text. Currently, I have the date displayed at the top of my website like this u ...

Combining two strings within a JSX element in React-Native

I'm currently receiving values from props and need to concatenate them before placing them in a JSX text element. However, I've been unsuccessful in my attempts to append the values together. Is there a workaround for this issue without having to ...

"activeStyle" attribute consistently being implemented on links within pagesindex.js

Just starting out with Gatsby/React and web development in general, so apologies if this is an easy fix. I'm facing an issue that I can't seem to solve. Currently, I'm working on my website's header and trying to create links to naviga ...

Disappearance of logo div causes video to vanish

Hey there fellow coders! I'm facing a little issue. I'm attempting to replicate my webpage on another page, but every time I try to remove the logo, the video disappears as well. It's quite puzzling. I have the code in place, but it seems l ...

Position a modal in the vertical center with scroll functionality for handling extensive content

Looking for ways to tweak a Modal's CSS and HTML? Check out the code snippets below: div.backdrop { background-color: rgba(0, 0, 0, 0.4); height: 100%; left: 0; overflow: auto; position: fixed; top: 0; width: 100%; z-index: 2020; } ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...