Skip to content

Instantly share code, notes, and snippets.

@baralong
Last active May 28, 2021 03:14
Show Gist options
  • Save baralong/4c6bfef3d4aedd2952de4c85797a7c42 to your computer and use it in GitHub Desktop.
Save baralong/4c6bfef3d4aedd2952de4c85797a7c42 to your computer and use it in GitHub Desktop.
react-native snippets

react-native-snippets

Just some things I found useful in my react-native development.

  • LockToPortrait.ts uses the react-native-orientation plugin and the event in react-navigation-stack
  • TextToFit.tsx a bit of a kludge, reduces font size by a 0.25 until it fits the required size. Uses opacity to hide until it's rendered
import { createStackNavigator } from "react-navigation-stack"
import { createAppContainer, NavigationAction, NavigationState } from "react-navigation"
import Orientation from 'react-native-orientation'
import Home from "./app/Home/Home"
import Contact from "./app/Home/Contact"
export default () => {
const RootStack = createStackNavigator({
Home: {
screen: Home,
navigationOptions: {
headerShown: false
},
params: { lockPortrait: true },
},
Contact: {
screen: Contact,
navigationOptions: {
headerShown: false
},
params: { lockPortrait: true },
},
}
const App = createAppContainer(RootStack);
const handleNavigationStateChange = (
prevNavigationState: NavigationState,
nextNavigationState: NavigationState,
action: NavigationAction) => {
const nextRoute = nextNavigationState.routes[nextNavigationState.index]
if(nextRoute && nextRoute.params && nextRoute.params.lockPortrait) {
Orientation.lockToPortrait()
} else {
Orientation.unlockAllOrientations()
}
},
{
initialRouteName: routes.home,
});
return <App onNavigationStateChange={handleNavigationStateChange}/>
}
import React, { useState } from "react"
import { StyleSheet, Text, TextLayoutEventData, TextProps } from "react-native"
interface TextToFit extends TextProps {
onFitComplete?: (size: number) => void;
}
export const TextToFit = (props: React.PropsWithChildren<TextToFit>) => {
const baseStyle = StyleSheet.flatten(props.style)
const baseOpacity = baseStyle.opacity || 1
const [fontSize, setFontSize] = useState(baseStyle.fontSize || 20)
const [opacity, setOpacity] = useState(0)
const numberOfLines = props.numberOfLines || 1
const onTextLayout = (event: TextLayoutEventData) => {
if(event.lines.length > numberOfLines) setFontSize(state => state - 0.25)
else {
setOpacity(baseOpacity)
props.onFitComplete && props.onFitComplete(fontSize)
}
}
return <Text
{... props}
style={[baseStyle, {fontSize: fontSize, opacity: opacity}]}
onTextLayout={({nativeEvent}) => onTextLayout(nativeEvent)}
>{props.children}</Text>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment