Set Background to an Image for Save to gallery - react-native

I have a qr-code in my react-native project from react-native-qrcode-svg like this:
<QRCode
value={singleTicketResponse.voucher}
size={width * 0.5}
getRef={(c) => (svg = c)}
/>;
I want to save this QR to the gallery! I use this code for saving it to gallery!
svg.toDataURL((data) => {
RNFS.writeFile(
RNFS.CachesDirectoryPath + `/${tracking_code}.png`,
data,
"base64"
)
.then((success) => {
return CameraRoll.save(
RNFS.CachesDirectoryPath + `/${tracking_code}.png`,
"photo"
);
})
.then(() => {
onClose();
})
.catch((e) => {
console.log("saveToGallery", e);
});
});
Now I want to save this QR with white background in the gallery!
Because now, I save QR to gallery and gallery show this in black background and scanner does not detect QR-code!!! Is there any solution??
In other words, how to combine two images (white background and QR-code) or how to set a background for this image??

You can simply add quietZone props to QRCode component. This props is the margin around the QR-code and when yo save the QR it is shown!!
<QRCode
value={singleTicketResponse.voucher}
size={width * 0.5}
quietZone={10} // this props
getRef={c => (svg = c)}
/>

Related

How to only load/render custom rendered image when it comes into view (react-native-render-html)

I am using react-native-render-html to render content that has images in it via a custom renderer. The issue I'm running into is some pages have dozens of images, and I would like to only download/render the ones I need that are in or near the viewport. The way the custom renderer is set up currently (via the documentation) it downloads all of them at once (How would I go about Implementing the logic into a more flatlist-like render system?
Here's the image renderer (if it helps):
const ImgRenderer = useCallback((props: any) => {
console.log('imgRendererProps: ', props)
const { Renderer, rendererProps } = useInternalRenderer('img', props);
const uri = rendererProps.source.uri;
const imgSource = {
...rendererProps.source,
// You could change the uri here, for example to provide a thumbnail.
uri: `https://home.website.com${uri?.split('about://')[1]}`
};
return (
<TouchableWithoutFeedback onPress={() => setModalImage(uri?.split('about://')[1] ?? null)}>
<Renderer {...rendererProps} source={imgSource} style={{resizeMode: 'contain'}} />
</TouchableWithoutFeedback>
);
}, [props.tnode?.init.nodeIndex])

React Native on Android focus doesn't open the keyboard

We are facing some very weird issue with opening keyboard on Android device.
It works great on iOS, 90% on Android devices, but on some devices it simply don't work = the keyboard don't show despite the input field has focus.
We tried it with different approaches (with refs, with timeout and without ref either).
All with the same result :/. One of the devices we are trying has API 30, so it even doesn't seem to be an old API problem.
Have anybody facing similar issue? What can cause the issue? Any tips how to debug it?
Here is code:
export const AddNotificationModal: AddNotificationModalT = ({
visible,
category,
onCloseModal,
}) => {
const input = useRef<TextInput>(null);
...
useEffect(() => {
if (visible) {
// 1.
// InteractionManager.runAfterInteractions(() => {
// if (input?.current) {
// input.current.focus();
// }
// });
// 2.
input.current?.focus();
// 3.
// setTimeout(() => input.current?.focus(), 150);
}
}, [visible]);
return (
<Modal
name={AddNotificationModal.name}
visible={visible}>
...
<View>
<TextInput autoFocus={true} ref={input} />
<Button dark onPress={() => onConfirm()}>
{t('shared:buttons.safe')}
</Button>
</View>
</Modal>
);
};

How do I get the current item displayed in a FlatList?

I'm using a flatlist to render a feed of videos for my project. I want to prevent the videos from auto-playing when they're not visible on the screen.
I figured the simplest way to do this would be to see if the current video on the screen is currently visible/active and if so, I can set props to true for playing etc.
I'm having a lot of issues trying to achieve this however an I wanted to know if anyone can give me some pointers as I'm new to React-Native.
You can use onViewableItemsChanged prop from FlatList
Docs Here
Working Example of FlatList of Videos with automatic play/pause feature
Something as shown below
const [Viewable, SetViewable] = React.useState([]);
const ref = React.useRef(null);
const onViewRef = React.useRef((viewableItems) => {
let Check = [];
for (var i = 0; i < viewableItems.viewableItems.length; i++) {
Check.push(viewableItems.viewableItems[i].item);
}
SetViewable(Check);
});
const viewConfigRef = React.useRef({ viewAreaCoveragePercentThreshold: 80 });
<FlatList
data={Videos}
keyExtractor={(item) => item._id.toString()}
renderItem={({ item }) => <VideoPlayer {...item} viewable={Viewable} />}
ref={ref}
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfigRef.current}
/>

React native how to Animate Text and Image

Hi everyone I just want to animate text and image. This code I wrote is animating at the beginnig.When I update the state, animation is gone just changing image and text. How can I fix it.
//the package I installed from npm
import * as Animatable from 'react-native-animatable';
//the images array changes by state
var arr=[{image:require('./assets/img1.png')},{image:require('./assets/img2.png')},{image:require('./assets/img3.png')}];
//The initial state
state = {
uri: require('./assets/img1.png'),
message:"-",
img_rank:0
};
//In onpress method of TocuhableOpacity
<TouchableOpacity
onPress={() => {
const randomIndex = Math.floor(Math.random() * 3);
//state of message
this.setState({ message: "Act1" });
//state of image rank from the array
this.setState({ img_rank: randomIndex })
...
Showing the text and image
//it's showing the image with animation at the beginning
<Animatable.Image source={arr[this.state.img_rank].image} animation="zoomInUp">
</Animatable.Image>
//the text but it's not animating
<Animatable.Text animation="zoomInUp">
<Text>{this.state.message} </Text>
</Animatable.Text>
Thank you.
Firstly, get your animated component's ref into a variable in your class like animatedImageRef.
<Animatable.Image
ref={r => this.animatedImageRef = r}
source={arr[this.state.img_rank].image}
animation={this.state.img_rank ? 'zoomInUp' : undefined}>
</Animatable.Image>
Then, in your onPress function, use this ref to animate your component again.
this.animatedImageRef.startAnimation(500, 0, () => { })

Programmatically set scroll index of react native VirtualizedList

I have a book reader application, I implement book content thorough react native Virtuallist. In some case it needs to scroll to some titles in the book that can be out of screen and not rendered yet. If I load whole book's content I faced some performance issue. I need a way to change Virtuallist index or shift it on paragraph selection. this is what I implemented so far but it scroll to bottom constantly to render paragraph I chose, And looks so ugly.
const getItem = (_, index, focusedRank) => {
return data[index];
};
return (
<VirtualizedList
ref={(refs) => (flatListRef.current = refs)}
data={DATA}
initialNumToRender={20}
renderItem={renderItem}
keyExtractor={keyExtractor}
getItemCount={() => data.length}
getItem={(_, index) => getItem(_, index, focusedRank)}
contentContainerStyle={{padding: 10}}
onScrollToIndexFailed={(info) => {
const wait = new Promise((resolve) => setTimeout(resolve, 500));
wait.then(async () => {
flatListRef.current.scrollToOffset({
offset: info.averageItemLength * info.index,
animated: true,
});
await flatListRef.current?.scrollToIndex({
index: focusedRank,
animated: true,
});
});
}}
/>
)
If I could change index or shift by focusedRank the problem's solved.
Why don't you use Flatlist. And also Flatlist has onLayout you could implement it using regression algorithm or like that. By implementing it you have a simple time to navigate between paragraph anymore