Home > Mobile >  How to show text when I click on button in react native?
How to show text when I click on button in react native?

Time:09-01

I am trying to create a simple question-answer app, I shared the example of my code below, on the below example how can I hide the Answer by default and show the answer when I click on the button?

import React, { useEffect, useState } from "react";
import {View, Text, StyleSheet, Button} from 'react-native'
const Testing = ({ navigation }) =>{

 return (
  <View style={{
    backgroundColor: '#f1f1f1',justifyContent: 'center', alignItems: 'center',}}>

    <Text>1. In which of the following languages is function overloading not possible?</Text>
    <Text>
1. C 
2. C  
3. Java
4. Python
</Text>
<Text>Answer: C</Text>
<Button title="Show Answer"/>

<Text>2.What is Lorem Ipsum?</Text>
    <Text>
1. Lorem
2. Ipsum
3. dummy
4. text
</Text>
<Text>Answer: Lorem</Text>
<Button title="Show Answer"/>
</View>

);}
export default Testing;

CodePudding user response:

Add state showAnswer, conditional render and button click event handler

import React, { useEffect, useState } from "react";
import {View, Text, StyleSheet, Button} from 'react-native'
const Testing = ({ navigation }) =>{

const [showAnswer, setShowAnswer] = useState(false);

return (
  <View style={{
    backgroundColor: '#f1f1f1',justifyContent: 'center', alignItems: 'center',}}>

    <Text>1. In which of the following languages is function overloading not possible?</Text>
    <Text>
1. C 
2. C  
3. Java
4. Python
</Text>
<Text>Answer: C</Text>
<Button title="Show Answer"/>

<Text>2.What is Lorem Ipsum?</Text>
    <Text>
1. Lorem
2. Ipsum
3. dummy
4. text
</Text>
{showAnswer && <Text>Answer: Lorem</Text>}
<Button title="Show Answer" onClick={() => setShowAnswer(prev => !prev)} />
</View>

);}

export default Testing;

CodePudding user response:

To achieve this effect I recommend you use a state with a boolean type, so true or false

Like this:

const [showValue, setShowValue] = useState(false);

then on the area where you want the text to render use a Ternary Operator

{showValue? <Text>Answer: Lorem</Text> : null}

When the showValue state is true React will render out the text

then give the button an OnClick() Like so

<Button title="Show Answer" onClick={() => setShowValue(!showValue)} />

Which will toggle the state between true and false

CodePudding user response:

One way of doing this is too have each question and answer pair be a component

<Text>Answer: C</Text>
<Button title="Show Answer"/>

and the component would look something like this

import React, { useState } from "react";
const Answer = ({ answerText }) => {

   const [showAnswer, setShowAnswer] = useState(false);
   return (
     {showAnswer ? <Text>{answerText}</Text> : ""}
 
     <Button onClick={()=>setShowAnswer(!showAnswer)} 
     title={showAnswer ? "Click to hide" : "Click to show"}/>
   );}

export default Answer;
  • Related