Search code examples
reactjsreact-nativejsxonpress

Return JSX component onPress react-native


I want to prompt users to get input onPress but returning JSX from an onPress never worked so whats a possible workaround to return JSX based on button click. Here's my code:

import React, { useState } from 'react';
import {
    StyleSheet,
    KeyboardAvoidingView,
    View,
    Text,
    TouchableOpacity
} from 'react-native';
import InputPrompt from './InputPrompt' 

const Newact = (props) => {
  const [visible, setVisible] = useState(false)
    return(
        <View>
            <View style={styles.button} >
            <TouchableOpacity  style={styles.center} onPress={getTitle}>
                    <Text style={styles.plusSign}>+</Text>
                    </TouchableOpacity>
            </View>
        </View>
    );
}
 
const getTitle = () =>{
  return(
    <InputPrompt />
  )
}

Update:

Now thats how my code looks:

const Newact = props => {

  const [prompt, setPrompt] = useState(false);

    return(
            <View style={styles.button} >
            <TouchableOpacity  style={styles.center} onPress={() => setPrompt(true)}>
                    <Text style={styles.plusSign}>+</Text>
                    </TouchableOpacity>
                   {prompt ? <InputPrompt setPrompt={setPrompt} />  : null}
            </View>
    );
}

and InputPrompt component is:

const InputPrompt = (props) => {
    const [name, setName] = useState('');

    return(
        <View>
        <DialogInput 
                     title={"New Activity"}
                        submitText={"Add"}
                        hintInput ={"Enter activity name....."}
                        submitInput={ (inputText) => {setName(inputText), props.setPrompt(false)} }
                        closeDialog={ () => {props.setPrompt(false)}}>
        </DialogInput>
        <Text>{name}</Text>
        </View>
    );
}

Solution

  • When they press, you should set state. This causes the component to rerender, and on that new render you can return JSX describing what you want the screen to look like. I'm not sure exactly where you want to render the input prompt, but maybe something like this:

    const Newact = (props) => {
        const [visible, setVisible] = useState(false)
        const [prompt, setPrompt] = useState(false);
        return (
            <View>
                <View style={styles.button} >
                <TouchableOpacity style={styles.center} onPress={() => setPrompt(true)}>
                    <Text style={styles.plusSign}>+</Text>
                </TouchableOpacity>
                </View>
                {prompt && <InputPrompt />}
            </View>
        );
    }