What is the best method for designing styles for a Reason-React component that are based on the props?

To gain knowledge in and , I am currently developing a straightforward “Things 2 Do” application (view source code on GitHub).

I have implemented a TodoItem component that should display with a strike-through style when the task is marked as completed.

My approach involves creating a record with different styles resembling CSS classes, one for the base style and another for completed items.

type style = {
  root: ReactDOMRe.style,
  completed: ReactDOMRe.style
};

let styles = {
  root: ReactDOMRe.Style.make(), /* define root styles here */
  completed: ReactDOMRe.Style.make(~opacity="0.666", ~textDecoration="line-through", ())
};

If the completed prop is set to true, I merge the base style with the completed style; otherwise, I only use the base style as shown below:

let style = styles.root;
let style = item.completed ? ReactDOMRe.Style.combine(style, styles.completed) : style;

Although this method works, it feels a bit cumbersome. Therefore, I am curious if there is a more elegant solution, like leveraging variants and switch statements?

What is the preferred way to define styles for a Reason-React component that are dependent on props?

Below is the complete code snippet of my component:

type item = {
  id: int,
  title: string,
  completed: bool
};

type style = {
  root: ReactDOMRe.style,
  completed: ReactDOMRe.style
};

let str = ReasonReact.stringToElement;

let component = ReasonReact.statelessComponent("TodoItem");

let styles = {
  root: ReactDOMRe.Style.make(), /* define root styles here */
  completed: ReactDOMRe.Style.make(~opacity="0.666", ~textDecoration="line-through", ())
};

let make = (~item: item, ~onToggle, _) => {
  ...component,
  render: (_) => {
    let style = styles.root;
    let style = item.completed ? ReactDOMRe.Style.combine(style, styles.completed) : style;
    <div style>
      <input
        _type="checkbox"
        onChange=((_) => onToggle())
        checked=(Js.Boolean.to_js_boolean(item.completed))
      />
      <label> (str(item.title)) </label>
    </div>
  }
};

Answer №1

There doesn't seem to be a definitive idiomatic approach yet in this rapidly evolving field. I am constantly considering different ideas for optimizations in my own work, but for now, here is how I currently implement it using bs-css:

module Styles = {
  open Css;

  let root = completed => style([
    color(white),
    opacity(completed ? 0.666 : 1.),
    textDecoration(completed ? LineThrough : None)
  ]);
}

...

  render: _self =>
    <div className=Styles.root(item.completed)>
      ...
    </div>

Answer №2

Currently, I am satisfied with how I am styling my component. There isn't a definitive approach for styling React components in Reason at this time.

In the Reason documentation it is mentioned:

Given the current popularity of CSS-in-JS, we will soon recommend our official choice. In the meantime, for inline styles, you can use the ReactDOMRe.Style.make API.

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

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

The presentational component undergoes constant re-rendering

UPDATE: After thorough investigation, I have identified the issue. It seems to be related to the code snippet in the third component that I shared earlier. The main problem lies in the function calls for goToBook and selectBook. My goal is to enable users ...

The typeof() operator in Javascript is providing unexpected results when checking the variable type

Hello, I have encountered an interesting issue while using console.log(typeof(variable) compared to console.log(variable). When I check the console, the variable appears to be an array of objects. However, when I use typeof, it shows as an object. I a ...

Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you c ...

Enhancing the aesthetic appeal of a form

I have created a form in HTML that utilizes JavaScript to pull data from a database. I am looking to style the form, but I'm unsure of how to proceed. Below is the form along with some CSS code. How can I integrate the two together? <form id=" ...

Stylish Button Action in conjunction with React MUI Alert

How can I style a button in an alert action using React MUI? My CSS changes are not being recognized. Do I need to pass parameters in a specific way? React: const StyledButton = styled(Button)` font-family: 'Source Sans Pro'; padding-bottom: 1 ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Styling List Markers with Material UI: A Guide to Using SX Props

Here is a follow-up question answered : Material UI - hierarchical ordered list If I have a list in Material UI with markers like this, <List sx={{ listStyle: "decimal", pl: 4 }}> <ListItem sx={{ display: "list-item" }}> ...

Function that activates traffic lights

Currently, I'm encountering errors while working on this project in Notepad. Can you help me figure out what's wrong with my code? I'm attempting to create an onload traffic light using an object array. The requirement is to implement this f ...

Using CDN to bring in Bootstrap, without triggering animations

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>E ...

TS will not display an error when the payload is of type Partial

Why doesn't TypeScript throw an error when making the payload Partial? It seems to only check the first value but not the second one. type UserState = { user: User | null; loading: boolean; error: Error | null } type UserAction = { type: type ...

Despite having the correct image URLs, the images are failing to display in the custom section of Shopify

Currently, I'm in the process of developing a unique Shopify section that showcases text alongside images. To enable users to upload images via the theme customizer, I have implemented the image_picker settings within the schema. The issue I am facing ...

What steps are involved in creating a nextjs application?

When I run the command npm run build to generate an optimized production build for my nextjs project, I am facing an issue where the build folder is not being created or it is not located under the .next folder. This is causing a problem as I need the bu ...

Can anyone provide guidance on how to trigger an HTTP 500 error in my React.js and Next.js applications?

To ensure that our custom error page is displayed instead of the default HTTP 500 error following a recent security vulnerability, I am looking to purposely simulate the error. While we have special processing in place for 404 and 403 errors on our site, ...

Is it possible to adjust the vertical background-position independently?

While creating a navigation bar using the <ul> element, I have come up with the following CSS code: .nav { list-style: none; background: url(/images/nav.png) no-repeat; width: 666px; height: 60px; } .nav li { font-size: 0px; backgr ...

Creating a personalized CSS class for TYPO3 menu links

I am currently in the process of creating a brand new website using TYPO3 6.2 and incorporating the Bootstrap Package. My goal is to be able to assign custom CSS classes to menu links directly from the backend, and then display these CSS classes within my ...

When a div slides down on page load, the div will slide up when a button is clicked

I am trying to make a div slideDown on page load. The goal is to have the div automatically slideDown after 2 seconds, which contains a responsive image and a button named "z-indexed". However, I am having trouble getting the same div to slideUp when the z ...

Error: The property 'fixtures' of an undefined object cannot be accessed. This issue arose from trying to access nested JSON data after making

Struggling with asynchronous calls, JS, or React? Here's my current challenge... Currently, I am using the fetch library to display a table based on data structured like this (note that there are multiple fixtures within the fixtures array): { " ...

Troubleshoot: Unable to Change CSS on Click Using Javascript/jQuery

Having trouble creating three different buttons that toggle between various images using the CSS display property? Check out my code on https://jsfiddle.net/agt559e8/. function USradarChange1() { //document.getElementById("usradar1").src="weather/curr ...

What is the method to alter the fill of a circle using CSS when it is hovered over in JavaFX?

I am seeking assistance for a task involving a circle within an hBox. I would like the color of the circle to change when the mouse cursor hovers over it. Is there a way to accomplish this using JavaFX and CSS? If not, what is the recommended approach fo ...