Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Styled components dynamic font sizing

Let's say i have a basic, base level StyledText component;

import styled from 'styled-components/native'

const StyledText = styled.Text`
  font-size: 16px;
  color: pink;
`
export default StyledText

I then have an extension of that Text component that handles titles;

import StyledText from '../StyledText'

const StyledTitle = StyledText.extend`
  color: black;
  font-weight: bold;
  font-size: 20px;
`

export default StyledTitle

Simple so far.

What i need to do is dynamically increase the font size based on the size of the device. A simple function can handle this. But is there a way that the sizing function or util can only be called once from the main StyledText component, rather than repeated throughout the app with EVERY instance of StyledText extension?

Just to clarify, there is not a problem surrounding the logic of increasing the size, the problem is importing and using the util for every single use of any extended Text component.

For example, the util might look like this;

// utils
export function fontSize(size) {
  // do some logic here to increase the size, or whatever...
  return `
    font-size: ${size}px;
  `
}

Then used like this;

import styled from 'styled-components/native'
import { fontSize } from 'utils/StyledUtils'

const StyledText = styled.Text`
  ${fontSize(16)}
  color: pink;
`
export default StyledText

The problem is that the util file has to be imported and referenced all the way through the app.

like image 763
Alex Avatar asked Oct 29 '22 23:10

Alex


1 Answers

I had similar problem a while ago, and I solved it by creating an universal function that takes size as argument and returns new size that fits on different screen resolution. You can use this function for every size in your app.

Here is the function inside file responsive.js:

import { Dimensions } from 'react-native'

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').height;

export const ResponsiveSize = (size) => {
    if(deviceHeight===568) { return size }
    else if(deviceHeight===667) size*1.17 
    else if(deviceHeight===736) size*1.29 
    else if(deviceHeight===1024) size*1.8 
}

Notice that size is multiplied by some fixed numbers (I did it for iOS devices) that you can modify to fit your needs.

Then you can style your text as following:

import styled from 'styled-components/native'
import { ResponsiveSize } from './responsive'

const StyledText = styled.Text`
  font-size: ResponsiveSize(16);
  color: pink;
`
export default StyledText
like image 99
krmzv Avatar answered Nov 15 '22 06:11

krmzv