What is the most effective method for sharing features while maintaining unique aesthetics?

In the process of developing a Next.js website, I've encountered a challenge:

I have 3 forms that function in similar ways but have different styles. Instead of duplicating code for each form, I'm looking for a way to build the form structure once and then style it differently without resorting to global CSS or inline styles.

My initial solution involves assigning a class to the form element and styling its children using traditional CSS. While this approach works, it feels out of place as the project primarily utilizes Styled-components. I'm seeking a solution that aligns with the principles of SC without relying on global styles.

This is what the current code setup looks like:

// form.js
export default Form = () => {
  /* ... hooks and stuff ... */  

  return (
    <form>
      /* ... */
    </form>
  )
}

// styled-form-1.js
import Form from './Form.js'

export default Form = () => {
  return (
    <Form className="styled-1" />
  )
}
// globalStyles.css
.styled-1 form { /* ... */ }
.styled-1 input { /* ... */ }
.styled-1 button { /* ... */ }

.styled-2 form { /* ... */ }
.styled-2 input { /* ... */ }
.styled-2 button { /* ... */ }

While the current solution is functional, I am eager to explore a Styled-components approach. I just haven't been able to find the right implementation yet.

Answer №1

One interesting feature of styled-components is the ability to pass a function to its template literal in order to customize styles based on props. For instance:

const Card = styled.div`
  background: ${props => props.highlight ? "yellow" : "gray"};
  color: ${props => props.highlight ? "black" : "white"};
  
  padding: 1em;
`;

render(
  <div>
    <Card>Regular</Card>
    <Card highlight>Highlighted</Card>
  </div>
);

This approach allows you to create versatile styled-components for your elements and adjust their appearance dynamically. To learn more, visit the official documentation.

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

JavaScript utilizing an API to retrieve specific data values

Below is some API Data that I have: [ { "symbol": "AAPL", "name": "Apple Inc.", "price": 144.98, "changesPercentage": -1.22, "change": -1.79, ...

Meteor NPM : The command `npm shrinkwrap` failed to execute

I've searched high and low for a solution to this issue, but I couldn't find one. I'm currently running a React - Meteor application with meteorhacks:npm and browserify. Error: While building the npm-container package: error: unable to run ...

Determine who the creator of the clicked div is

I'm sorry if my explanation is a bit difficult to comprehend. Here is the code snippet in question: names.push(newName); var strName = newName; var newName = document.createElement('p') newName.setAttribute('id', newName); documen ...

Utilizing checkboxes to narrow down JSON data results through jQuery/AJAX filtering

I'm currently working on developing a search page with advanced filtering capabilities. The goal is to have a sidebar that displays directors, ratings, and years without any duplicate entries. When a checkbox is selected, the filtered results of films ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Is it possible to utilize custom CSS to conceal commas and evade a JSX bug?

One element of my website relies on the following .js code snippet: items.add( `field-${field.id()}`, <div className="Mason-Field Form-group"> <label> {field.icon() ? <>{icon(field.icon())} & ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

When the mouse is moved to the UL LI list, the border color of the Top Hover is reverted back to default

Can you assist me with this issue? I need to modify the code below so that the border color remains blue while a user selects an item from the UL LI list. Here is an image showing the current problem: https://i.sstatic.net/DS7hO.png And here is a pictu ...

What is the best way to assign a dynamic width to a block element?

In my project, I am working with 30 elements that have the class .lollipop and are styled with line-height: 30px; height: 30px;. <a class="lollipop">Random text</a> <a class="lollipop">Random text longer</a> <a class="lollipop"& ...

React JS: The active text object in Fabric JS canvas becomes uneditable after attaching an event listener

After implementing event listeners for copy-paste, cut-paste, and movement functionalities in different directions, I encountered an issue when trying to edit the active text object on the canvas. I am utilizing the fabricjs-react module. Below is the cod ...

Troubleshooting problems with req.query, req.params, and req.body while working with express+axios in a MERN application

In my React code, I am attempting to make a call using axios: axios.get(`http://localhost:5000/daily_batches/num_tweets_by_tag_and_date/`, { params: { tag: "Green/Sustainable Energy", date: "2021-0 ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

What is the process for adjusting the color of the dots in the React MUI MobileStepper component

I'm having trouble figuring out how to change the color of the dots. I've made several adjustments in makeStyles, such as: dot: { backgroundColor: "#008000 !important" } but none of them seem to be working. You can view my code here. ...

Converting Javascript Variables into a PHP Script

After noticing that the same question was being asked repeatedly, I delved into thorough research to discover effective methods for transferring a couple of JavaScript variables to a PHP script. Include data in a form as hidden values Send to URL, like & ...

What is the best way to stop Quasar dropdown list from moving along with the page scroll?

I am facing an issue with my code while using Quasar (Vue 3.0). The code snippet in question is: <q-select filled v-model="model" :options="options" label="Filled" /> When the drop-down menu is open and I scroll the pag ...

How can you continuously calculate and show the total quantity of items in a list?

Currently, I have lists set up in my sidebar and I'm looking to include a label displaying the number of items within each list. To provide a better understanding of what I'm aiming for, I've put together a JSFiddle demonstration at the fol ...

Utilizing Bootstrap Modal to trigger an Action Result function when a button is clicked

I could use some assistance. In my current setup, I have a file picker that loads a file into a specific table in my database. When the user clicks a button, a bootstrap modal pops up to ask if they are uploading more files. This is how it looks in my vi ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

A pair of boxes sitting next to each other, both occupying 50% of the space but slightly longer in length and not aligned on the same level

My goal is to have two side-by-side boxes that fill the entire width of the screen. However, I'm facing an issue where each box exceeds 50% width by about 10 pixels. What could be causing this discrepancy? #sides { padding-top: 40px; padding- ...