I created two componentes :
component useImgPicker - custom hook:
- responsible to open the camera
- user can take a picture
- save the image url to imgUrl variable
return:
- someFunction (function that open the camera and save the url)
- imgUrl (the state - string)
- component App - use the custom hook
- use the custom hook
- after the user click on the button, diplayImg function activated
- diplayImg function use the custom hook, and make change to hasTakePicture variable (become true).
- after hasTakePicture become true -> new
<View>render with
the desire: the source url inside the <Img> will change to the newUrl
the result: the value of newUrl inside <Img> is the same, but inside <Text> {newUrl} </Text> the newUrl is change
component ImgPicker - custom react hook
import {useState} from 'react';
const useImgPicker = ()=>{
const [imgUrl, setImgUrl] = useState(''); //string
const someFunction = ()=>{
// make chang to imgUrl
const newUrl = "/some dumi url.png"
setImgUrl(newUrl);
}
return{ imgUrl, someFunction }
}
export default useImgPicker;
component App - use the custom hook
import React,{useState} from 'react';
import useImgPicker from './ImgPicker.js'
const App = ()=>{
const { imgUrl, someFunction } = useImgPicker ();
const [hasTakePicture, setHasTakePicture] = useState(false);
const diplayImg = ()=>{
someFunction();
setHasTakePicture(true);
console.log(imgUrl); // here the value of imgUrl is -> '' empty (default value)
}
return(
{hasTakePicture ? (
<View>
// inside the 'source' prop of the Image the value of imgUrl-> '' empty (default value)
<Image style={styles.image} source={{uri: imgUrl}} resizeMode='contain'/>
{imgUrl} // -> here the value of imgUrl is -> newUrl
</View>
) :
(
<View></View>
)
}
<Button title="Take Picture" onPress = {diplayImg } >
)
}