0

I've been trying to apply this to each component or to the main index.js component. However, none of those methods are working so far.

import React from 'react';
import { render } from 'react-dom';
import { Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import { store } from './store/index';
import history from './history';
import 'semantic-ui-css/semantic.min.css';

import Div100vh from 'react-div-100vh';

import registerServiceWorker from './registerServiceWorker';

import App from './components/App';
// import '../public/index.css';

render(
  <Provider store={store}>
    <Router history={history}>
      <Div100vh>
        <App />
      </Div100vh>
    </Router>
  </Provider>,
  document.getElementById('root')
);
registerServiceWorker();

This is my index.js and this works great with the desktop browsers. However, I still have the scrollbar on mobile browsers. I bet I have done something wrong here. I really have no clue what to do. Do I have to do <Div100vh> every parent component?

chichi
  • 2,777
  • 6
  • 28
  • 53
  • I've encountered this issue recently. I've had issues specifically for iOS. Check this out: https://stackoverflow.com/questions/37112218/css3-100vh-not-constant-in-mobile-browser – 95faf8e76605e973 Sep 26 '20 at 03:42
  • I read about those. Trying to apply this to my react app but nothing really works for now :/ – chichi Sep 26 '20 at 04:40

1 Answers1

1

I am a front-end noobe, and i have encountered the same problem in my own project. I created a hook myself to solve this problem, and it performed well.

import { useSafeState, useEventListener } from 'ahooks';
// you can replace it with the hook provided by react, useState, useLayoutEffect
// the same function

/**
 * Solve the problem of abnormal display of 100vh on the mobile browser
 * return real 1vh
 * @returns {Number|null}
 * On the desktop browser return null
 */
export default function use1vh() {
    const [vh, setVh] = useSafeState(
        (document.documentElement?.clientHeight || window.innerHeight) * 0.01,
    );

    useEventListener('resize', () => {
        setVh(
            (document.documentElement?.clientHeight || window.innerHeight) * 0.01,
        );
    });

    // if device is mobile
    if (
        RegExp(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i).test(
            navigator.userAgent,
        )
    ) {
        return vh;
    } else {
        return null;
    }
}

How to use ↓

// init
const oneVh = use1vh();

// If you use styled-components
const SomeComponent = styled.div`
height: ${({ oneVh }) => {
    if (oneVh) {
        return `${100 * oneVh}px`;
    } else {
        return '100vh';
    }
}};

<SomeComponent oneVh={oneVh} />


// If you use css, less, sass, postcss, etc.
<div style={{height: oneVh ? oneVh*100 + 'px' : '100vh' }} />

It works great for me.

Yernar.T
  • 44
  • 5