0

I want to create a reusable code for different screen sizes. I'm using createContext API so that I wont get to rewrite the code in different screen. I got this error

null is not an object (evaluating '_useContext.width)

Btw, I'm using the useWindowDimensions() from react native https://reactnative.dev/docs/usewindowdimensions. Here's the code.

theme.js

import React, {createContext, useState, useEffect} from 'react';
import {useWindowDimensions} from 'react-native';

export const WindowContext = createContext();

export const DefaultTheme = ({children}) => {
  const WIDTH = useWindowDimensions().width;
  const HEIGHT = useWindowDimensions().height;

  const [width, setWidth] = () => useState(WIDTH);
  const [height, setHeight] = () => useState(HEIGHT);

  useEffect(() => {
    const handleSize = () => setWidth(WIDTH);
    setHeight(HEIGHT);
    window.addEventListener('resize', handleSize);
    return () => window.removeEventListener('resize', handleSize);
  }, []);

  return (
    <WindowContext.Provider
      value={{
        width: width,
        height: height,
      }}>
      {children}
    </WindowContext.Provider>
  );
};

and I want to implement the code on my button component

button.js

import React, {useContext} from 'react';
import {WindowContext} from '../../theme';

const Button = ({buttonTitle, textColor, ...rest}) => {
  const {width} = useContext(WindowContext);

  return (
    <>
      {width < 376 ? (
        <DefaultButton height="50" {...rest}>
          <ButtonText color={textColor}>{buttonTitle}</ButtonText>
        </DefaultButton>
      ) : (
        <DefaultButton height="60" {...rest}>
          <ButtonText color={textColor}>{buttonTitle}</ButtonText>
        </DefaultButton>
      )}
    </>
  );
};

export default Button;
amrxlamn
  • 3
  • 4

1 Answers1

0

you can get screen width like this:

import {Dimensions} from 'react-native';

const { width: screenWidth } = Dimensions.get('window')