styled-components: expand designs and alter type of element

Imagine I have these specific styles:

color: black;
border: 1px solid white;

and now I want to apply them to two different elements:

const SomeImg = styled.img`
  margin: 2em;
`;

const SomeDiv = styled.div`
  margin: 3em;
`;

How can I make sure that both elements inherit those styles?


If they were both <div> or <img>, it would be simple. Here's how:

const ExtendMe = styled.div`
  color: black;
  border: 1px solid white;
`;

const SomeDiv = styled(ExtendMe)`
  margin: 2em;
`;

const OtherDiv = styled(ExtendMe)`
  margin: 3em;
`;

Answer №1

If you want to change the HTML tag of your component, you can use the "as" prop from styled-components. Check out this link for more information:

Here's an example of how you can achieve this:

const CustomStyle = styled.div`
  color: black;
  border: 1px solid white;
`;

const ImageComponent = styled(CustomStyle).attrs({
  as: "img"
})`
  margin: 2em;
`;


const DivComponent = styled(CustomStyle)`
  margin: 3em;
`;

You can view a live example here: https://codesandbox.io/embed/mj3j1xp6pj?fontsize=14

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

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

Is there a way to retrieve data from Apollo-Server in nodeJs without relying on React?

Is there a way to fetch data from Apollo-Server (GraphQL) without using React? I tried using node-fetch based on some tutorials but it didn't work as expected. Here is the code snippet I used for fetching data: const getData = (query)=>{ return fe ...

Is it possible to stop JSON.stringify from invoking the toJSON method?

JSON.stringify provides a way for objects to customize their serialization process by defining a function named toJSON. Here is an excerpt from the MDN documentation: toJSON() behavior If an object being converted to a string has a method called toJSON, ...

A beginner's guide to efficiently indexing tables in AngularJS

Having Trouble with ng-repeat Indexing <tr ng-repeat="Ward in Wardresult "> <td>{{$index + 1}}</td> ...................... some column ....................... </tr> Although, the output ...

reduce the size of the image as the browser width decreases

Struggling with a webpage layout that features an image on the left and content area on the right, both with fixed widths. When reducing browser width, the image should not shrink but be cropped from the left side instead. Any solutions for this issue? ...

What are some practical ways to incorporate JQuery into a ReactJS project?

Exploring the world of ReactJS for beginners, I am faced with a challenge. I have created a navigation bar that should stick to the top of the page when scrolled past 100px. Here is the code for my navigation bar: Navigation Bar Component Code: export de ...

Is there a way to insert a button within a table that will allow me to easily insert new rows and columns?

<head> No content available at the moment. <!-- Here is my code --> <h1>Reserve Your Hall Form</h1> <form class="form-horizontal"> <table class="form-group table table-bordered table-hover"> ...

After an ajax request, the Jquery hover effects are no longer functional

On my website, I have implemented ajax calls to filter product results and apply effects. However, the effects on these products seem to stop working after the ajax call is completed. Located at the bottom of the page's code is the following script: ...

The width of the Bootstrap tooltip changes when hovered over

Currently, I am facing a peculiar issue with my angular web-application. Within the application, there is a matrix displaying data. When I hover over the data in this matrix, some basic information about the object pops up. Strangely, every time I hover ov ...

Displaying Images on top of Images with React/Javascript/NextJS

I have two images. Let's say image 1 is a thumbnail for news content. I would like to overlay a promotional PNG banner on top of this image and create a new output image. This output image will be used as the OG (Open Graph) image. How can I achieve t ...

The validation of form.$invalid appears to be malfunctioning when using the Angular UI date picker

There are two fields on the form, one for selecting a due date and another for entering a number. The due date field is a date picker where you can choose a date or manually enter a number to set the date. The create button gets enabled only when setting ...

I possess a compilation of URL links and I am seeking to identify the specific HTML div that corresponds to each URL within a webpage

Could you please help me figure out which HTML div each URL belongs to on a webpage using Java? I have a list of URLs that need to be matched with their respective HTML divs. ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...

JavaScript method parameters are essential components that help define the methods

Can someone explain how function definitions work within a method in Javascript? An example I'm struggling with is in AngularJS: sth.controller('ctrlname', function ($scope, $ionicModal, par3, par4){ //code }); Another piece of code ...

The error message "TypeError: Cannot read property 'location' of undefined" is caused by the connected-react-router using ReactRouter v5

https://i.stack.imgur.com/4Rpcw.png Hey there, I recently developed an application using React and Redux. While trying to handle redirection after a redux action, I came across the connected-react-router package from ReactRouter. Despite following the offi ...

Transmit data via XMLHttpRequest in smaller portions or through a ReadableStream to minimize memory consumption when handling large datasets

Recently, I've been experimenting with JS's XMLHttpRequest Class for handling file uploads. Initially, I attempted to upload files using the following code: const file = thisFunctionReturnsAFileObject(); const request = new XMLHttpRequest(); req ...

Having trouble locating an element, Sammy?

I am encountering an issue while using Sammy for my SPA. The error message I receive is: [Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get / Error: 404 Not Found get / at Sammy.Application.error (sammy-latest ...

"Using RxJS 6 for a countdown timer in an Angular 6 application

Currently, I am working on implementing a countdown timer in Angular 6 using RxJS 6. My goal is to have the ability to subscribe to the results and reset the timer as needed: Here is what I have tried so far: const timer = interval(1000).pipe( take(4) ); ...

Footer button overrides list components due to improper implementation of vertical ion-scroll

Having some trouble setting up ion-scroll on a specific screen in my mobile application built with Ionic. On the Book page of my app, I'm encountering two main issues: https://i.stack.imgur.com/MnheG.png 1) The placement of the Confirm button doesn& ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...