Utilizing the power of CSS' calc() function in ReactJS using react-motion's <Motion/>

I'm currently attempting to utilize calc() within a template string for the following scenario:

<Motion
  defaultStyle={{
    y: 0,
    opacity: 1
  }}
  style={{
    y: spring(this.state.navBarOpen ? 0 : `- calc(3.25em + 0.5vw)`),
    opacity: spring(this.state.navBarOpen ? 1 : 0)
  }}
>
  {style => (
    <NavBar
      style={{
        transform: `translateY(${style.y})`,
        opacity: style.opacity
      }}
      clickedOpenMenu={this.onClickMenuSwitchHandler}
    />
  )}
</Motion>

The challenge here is that there is a template literal nested inside another template literal, and I am uncertain how to resolve this issue to ensure the animation functions correctly.

The objective is to use the calc() function to dynamically resize the <NavBar/> based on font size and viewport dimensions, while also animating the <NavBar/> to move up in the Y-axis when scrolling down (to hide) and appear/move down when scrolling up. The animations are working fine, but integrating the calc() part is proving to be tricky.

If anyone has experience dealing with this type of situation, any guidance or insight would be greatly appreciated.

Thank you for your time and consideration!

Edit: For reference, here's a functional example of the desired outcome without using calc(): Example Link. The lack of calc() functionality is the main obstacle preventing full implementation.

Answer №1

Successfully resolved the issue by performing the calculation outside the <Motion> scope. Here is the modified approach:

let calc, vw, em

class Layout extends Component {

  componentDidMount(){
    vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
    em = scales.baseFont
    calc = 3.25 * em + 0.5 * 0.01 * vw
  }
  render () {

    return (
      <Motion
      defaultStyle={{
        y: 0,
        opacity: 1
      }}
      style={{
        y: spring(this.state.navBarOpen ? 0 : -calc),
        opacity: spring(this.state.navBarOpen ? 1 : 0)
      }}
      >
      {style => (
        <NavBar
          style={{
            transform: `translateY(${style.y})`,
            opacity: style.opacity
          }}
          clickedOpenMenu={this.onClickMenuSwitchHandler}
        />
      )}
      </Motion>
    )
  }
}

While this solution may not be optimal, it effectively resolves the issue. As a newcomer to programming, I am open to suggestions for improvement. If anyone has a better suggestion, please feel free to share! Always eager to learn.

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

Begin the API server along with the React server for your React application

I'm currently working on my first React app, and I'm facing a challenge in getting both the API and the React server to start simultaneously. For client routes, I am using react-router. In a previous project, I utilized Express for setting up th ...

Center the panel on the page and decrease its width using Bootstrap

I recently incorporated a Bootstrap panel above a search results table - my first experience working with Panels. This panel contains a form with a select menu, allowing users to filter the list of search results based on their selections. Currently, the ...

Differences between Default Values and undefined in React TypeScript Context

When using React with TypeScript, there is a decision to be made regarding whether default values should be defined for context or if the context value should be allowed to be undefined. Which option is generally recommended for better type safety, perform ...

"Using the d-flex class with Bootstrap 4 tables does not allow them to expand to

Since the latest version of Bootstrap 4, it has become more challenging to apply classes like col-md-2 directly to the tr or td elements of a table. A possible solution is to use class="d-flex" in the parent element: <tr class="d-flex"> However, w ...

Web element not detected within Span Tag

Within my HTML, I have the following: <span class="login-link">Log in</span> The code snippet I am using is: driver.findElement(By.cssSelector("#login > span")).click(); I have tried utilizing xPath, cssSelector, and id, but none of them ...

The issue of Storybook webpack failing to load SCSS files persists

I'm running into an issue where my styles are not loading in Storybook, even though I'm not getting any errors. Can someone help me out? My setup involves webpack 2.2.1. I've scoured Stack Overflow and GitHub for solutions, but nothing seem ...

Every time I try to install create-react-app, I keep encountering a frustrating 'network Socket timeout' error

$ npx create-react-app amazon-clone npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. Creating a new React app in D:\js\faceboom. npm WARN config global `--global`, `--local` are deprecated. ...

Bootstrap maximizes the utilization of the space in an adjacent column

I am currently working on a React project, and one of the pages includes a left sidebar that takes up 3 column spaces in the container. The main content of the page occupies the remaining width, using an additional 8 columns. The sidebar contains only 7- ...

How to vertically center a card between a search bar and the bottom of the viewport using Bootstrap?

I'm struggling to center a card vertically between the search bar and the bottom of the viewport. Even after setting the body height to 100%, the content extends beyond the viewport, leaving white space that users can scroll into. I've attempted ...

Utilizing responsive font sizing in material-ui: A step-by-step guide

My theme provider is functioning as expected, but the typography settings seem to be causing issues. Below is the theme provider code that has already been imported into the App file: import { createTheme } from '@mui/material/styles'; export c ...

During the testing phase, any code that triggers React state updates must be enclosed within the act function to ensure accurate

Encountering a familiar issue that has been posted on stackoverflow before, however, most of the similar queries remain unanswered. Despite passing the test, a warning is displayed. I attempted to resolve this by utilizing act(() => {}); but struggled t ...

Centered styled checkbox cannot be checked with TalkBack or VoiceOver enabled

I am currently testing the accessibility of a mobile web app I developed and have encountered an issue with checkboxes while using TalkBack on Android or VoiceOver on iOS. The problem arises from hiding the actual checkbox and presenting a styled label th ...

What is the method for accessing extra parameters in the signIn() callback function in [...nextauth]?

As per the Next Auth documentation, it is possible to pass extra parameters to the /authorize endpoint using the third argument of signIn(). The examples provided are: signIn("identity-server4", null, { prompt: "login" }) // always ask ...

Is there a way to align elements in a table cell (td) where one element is aligned to the left and the other to the right?

Given the html code shown below: <tr> <td>Some text <a href="">Some link</a> <button>Some Button</button></td> </tr> I am looking to achieve a layout where elements are positioned in different alignments ...

Managing data modifications on the server in single-page web applications

Imagine we are creating a forum application that operates on a single page. Various users have the ability to post new content at any given moment. How can this type of app detect when there is new data on the server, such as a recently added post? One ap ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...

The error message "window is not defined" may occur during the building process of NEXT

Every time I attempt to build my nextjs project, it fails and displays the error below. Curiously, the project functions flawlessly during development. I have not utilized 'window.' anywhere in my project, yet I keep encountering this error. I ha ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

Achieve vertical alignment in unordered lists with Bootstrap 4

Bootstrap4 documentation states that the predefined classes align-items-center and justify-content-center can be used to align contents vertically and horizontally. While testing the example provided in the Bootstrap4 document, it worked correctly. However ...

Updating the list state does not trigger a re-render in Next.js/React

Currently, I have the following state setup: const [places, setPlaces] = useState(false) const [selectedPlaces, setSelectedPlaces] = useState([]) I am asynchronously fetching data to populate the places state by calling an API. The returned array of objec ...