Search code examples
reactjstypescriptreact-nativereact-routerreact-router-native

React-Router-Native passing image as parameter


Im trying to pass image as my parameter on react-router-native and trying to get the data from the location.state but im having issue.

I usually do this to display image

Import Icon from '../image/icon.png';

<View>
  <Image source={icon} />
</View>

but i want to pass the icon to different page

Page1

import Icon from '../image/icon.png';

const nav = useNavigate();
const onClick = () => {
    nav('Page2/:icon', {state: {icon: Icon}})
}
<> 
   <touchableOpacitiy onpress={onClick} />
</>

Page2

let param = useLocation();

</>
   <Image source={param.state}>
</>

I receive the value in param.state but im having error when i set it on the image source because its unknown type. is there a best way to pass image parameter on the other page in react-router-native? im also using typescript on my pages.


Solution

  • First, give the location object a better name so it's harder to confuse with any "params"-type object (i.e. useParams).

    const location = useLocation();
    

    Then recast the state to a type you know.

    const state = location.state as { icon?: string };
    

    Then access the state object.

    <Image source={state} />
    

    Edit react-router-native-passing-image-as-parameter

    What seems to have specifically worked for the OP is casting to type any and passing directly state.icon.

    const state = location.state as any;
    
    ...
    
    <Image source={state.icon} />