Render JSX in react native - react-native

Let's say we have a jsx saved in a variable, can we render it in react native?
import {StyleSheet} from 'react-native';
const content = `<View style={styles.container}>
<Text>TESTING</Text>
</View>`;
const App = () => {
return {content};
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'blue',
},
});
export default App;
Getting the above error if I run that code.
How to implement this? Any example would be great.

Don't try to convert it into a string, then.
You could use just like this.
const content = <View style={styles.container}>
<Text>TESTING</Text>
</View>;
const App = () => {
return content;
};

Related

Show or Hide element or Style element by using ref or nativeID

How can I use the refText to update the element 'Text'
const refText = null;
const doSomething = () =>{
refText.changeVisibility("hidden"); // something like that
}
return <Text ref={refText} onPress={doSomething}>Some Text</Text>;
I tried to find any way to work with it, but can't find any solution over google. Or maybe I missed.
setNativeProps may be what you're looking for, however this is generally not the recommended way to make updates to an element. Instead, consider using state and updating relevant props/styles of your component in response to that state change:
Example on Expo Snack
import { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default function App() {
const [visible, setVisible] = useState(true);
return (
<View style={styles.container}>
<Button title="Toggle" onPress={() => setVisible(previous => !previous)} />
{visible && (
<Text onPress={() => setVisible(false)} style={{padding: 20}}>Click this text to hide it</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});

Customize Action Sheet Message (Expo)

I'm using #expo/react-native-action-sheet, and i want to show a button in the props message.
e.g
import { useActionSheet } from "#expo/react-native-action-sheet"
const { showActionSheetWithOptions } = useActionSheet()
const onPress = () => {
// Here
**const message = '<TouchableOpacity><Text>fsdf</Text></TouchableOpacity>'**
showActionSheetWithOptions(
{
message
},
(buttonIndex) => {
}
)
}
But it is not showing the button as i want
My purpose is to add a date picker in the action sheet.
Expecting answer:
In this case, you can use another library https://gorhom.github.io/react-native-bottom-sheet/ because Action Sheet is about the list of actions.
You can place any content you need for react-native-bottom-sheet and it also supports Expo
import React, { useCallback, useMemo, useRef } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import BottomSheet from '#gorhom/bottom-sheet';
const App = () => {
// ref
const bottomSheetRef = useRef<BottomSheet>(null);
// variables
const snapPoints = useMemo(() => ['25%', '50%'], []);
// callbacks
const handleSheetChanges = useCallback((index: number) => {
console.log('handleSheetChanges', index);
}, []);
// renders
return (
<View style={styles.container}>
<BottomSheet
ref={bottomSheetRef}
index={1}
snapPoints={snapPoints}
onChange={handleSheetChanges}
>
<View style={styles.contentContainer}>
<Text>Awesome 🎉</Text>
</View>
</BottomSheet>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 24,
backgroundColor: 'grey',
},
contentContainer: {
flex: 1,
alignItems: 'center',
},
});
export default App;

TouchableOpacity's onPress is not working

Task.js
export const Task = ({ addTask }) => {
const [focusItem, setFocusItem] = useState(null);
return (
<View style={styles.titleContainer}>
<Text style={styles.title}>What would you like to focus on?</Text>
<View style={styles.container}>
<TextInput
style={{ flex: 1 }}
maxLength={50}
value={focusItem}
onSubmitEditing={()=>({ nativeEvent: { text } }) => setFocusItem(text)}
/>
<RoundedButton
style={styles.addSubject}
size={50}
title="+"
onPress={()=>addTask(focusItem)}
/>
</View>
</View>
);
};
App.js
import React, { useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import {Task} from './src/features/task/Task'
export default function App() {
const [task, setTask] = useState(null);
return (
<View style={styles.container}>
{
task ?
(<Text></Text>):
(<Task addTask = {setTask}/>)
}
<Text>{task}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#425670',
},
});
I have tried to send the data from Task to App component by setting the value from Task. But onPress is not working.
I could see the text has been set successfully while executing the onSubmitEditing, but the onPress is doing nothing. Please help me fix this.
Thanks in advance
You need to change this
onSubmitEditing={()=>({ nativeEvent: { text } }) => setFocusItem(text)}
to
onSubmitEditing={({ nativeEvent: { text } }) => setFocusItem(text)}
You could also refer I want to update the parent according to the change of the child to react native

React Native - How to extract data from FaceDetector of Expo SDK?

I’m new to React Native and still learning React and JavaScript. I’m practicing on Expo snack with Expo's FaceDetector (SDK 37) and managed to generate data about faces. However, I couldn't (or don't know how to) extract these data. My goal for now is to render the rollAngle data in a Text component.
Here is the code I used in Expo Snack and tested with my Android cellphone:
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { Camera } from 'expo-camera';
import * as FaceDetector from 'expo-face-detector'
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [faces, setFaces] = useState([])
const faceDetected = ({faces}) => {
setFaces({faces})
console.log({faces})
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission !== true) {
return <Text>No access to camera</Text>
}
return (
//<View style={{ flex: 1 }}>
<Camera
style={{ flex: 1 }}
type='front'
onFacesDetected = {faceDetected}
FaceDetectorSettings = {{
mode: FaceDetector.Constants.Mode.fast,
detectLandmarks: FaceDetector.Constants.Landmarks.all,
runClassifications: FaceDetector.Constants.Classifications.none,
minDetectionInterval: 5000,
tracking: false
}}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<Text style= {{top:200}}> is {faces[0].rollAngle} </Text>
</View>
</Camera>
//</View>
);
}
In the snack console, I see results like this:
Results in the Snack console
I tried to replace the faceDetected function with the following code:
const faceDetected = (faces) => {
setFaces(faces)
console.log(faces)
}
Then, the console shows slightly different results: Results in Snack console
I tried both ways to render rollAngle, but an error message showed up and said face[0].rollAngle is undefined and is not an object.
Please help and any suggestion is appreciated.
Thank you.
You may have resolved this problem.
"faces.faces" worked for me..
const faceDetected = (faces) => {
setFaces(faces.faces)
}
I am new to react-native..
So if you resolved it by some other way please let us know.
I believe I have fixed your problem:
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { Camera } from 'expo-camera';
import * as FaceDetector from 'expo-face-detector'
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [faces, setFaces] = useState([])
const faceDetected = ({faces}) => {
setFaces(faces) // instead of setFaces({faces})
console.log({faces})
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission !== true) {
return <Text>No access to camera</Text>
}
return (
//<View style={{ flex: 1 }}>
<Camera
style={{ flex: 1 }}
type='front'
onFacesDetected = {faceDetected}
FaceDetectorSettings = {{
mode: FaceDetector.Constants.Mode.fast,
detectLandmarks: FaceDetector.Constants.Landmarks.all,
runClassifications: FaceDetector.Constants.Classifications.none,
minDetectionInterval: 5000,
tracking: false
}}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
{faces[0] && <Text style= {{top:200}}> is {faces[0].rollAngle} </Text>} // only render text if faces[0] exists
</View>
</Camera>
//</View>
);
}
I think your main problem was you were using
setFaces({faces})
instead of
setFaces(faces)

Facebook Login using Exponent React Native

Need help guys, currently using exponent and accessing the Exponent.Facebook.logInWithReadPermissionsAsync for authentication. Anyone has a guide in setting up the project. I can't find the iOS folder since in the instruction of facebook sdk, I need to add few libraries on the project. Here's my main.js:
import Expo from 'expo';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Button } from 'react-native-elements';
class App extends React.Component {
authenticate = (token) => {
const provider = firebase.auth.FacebookAuthProvider;
const credential = provider.credential(token);
return firebase.auth().signInWithCredential(credential);
}
login = async () => {
const ADD_ID = 273131576444313
const options = {
permissions: ['public_profile', 'email'],
}
const {type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(ADD_ID, options)
if (type === 'success') {
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`)
console.log(await response.json());
this.authenticate(token);
}
}
render() {
return (
<View style={styles.container}>
<Text>Open up main.js to start working on your app!</Text>
<Button
raised
onPress={this.login}
icon={{name: 'cached'}}
title='RAISED WITH ICON' />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Expo.registerRootComponent(App);
`
Try putting single quotes around the APP_ID