GrapeJam
GrapeJam

Reputation: 181

React Native: Show/Hide <Text> component by toggling icon button

I am trying to create a component which will have a list of components with data passed in through props.

However when the user first views the screen I'd like the text to be hidden by default and display an eight underscores, but when the user clicks an icon the text data passed in through props will be displayed.

Take the following example below for instance:

Data:

const data = {
First,
Second,
Third,
Fourth
}

Default Screen:

<View>
<Icon onPress()/>
<ul>
<li>
<Text>_ _ _ _ _ _ _ _ </Text
</li>
<li>
<Text>_ _ _ _ _ _ _ _ </Text
</li>
<li>
<Text>_ _ _ _ _ _ _ _ </Text
</li>
<li>
<Text>_ _ _ _ _ _ _ _ </Text
</li>
</ul>
</View>

After Pressing:

<View>
<Icon onPress()/>
<ul>
<li>
<Text> First </Text
</li>
<li>
<Text> Second </Text
</li>
<li>
<Text> Third </Text
</li>
<li>
<Text> Fourth </Text
</li>
</ul>
</View>

I am still new to React, particularly with manipulating state and am wondering how one could achieve something like the above?

Upvotes: 0

Views: 2502

Answers (2)

CevaComic
CevaComic

Reputation: 2104

What you need is a toggle to show or hide your texts.

Example here:

import React from 'react'
import { SafeAreaView, Text } from 'react-native'

const data = [
    "First",
    "Second",
    "Third",
    "Forth"
]

export default props => {

    const [show, setShow] = React.useState(false)
    const toggleText = () => setShow(show => !show)

    return (
        <SafeAreaView>
            <Text onPress={toggleText}>Toggle</Text>
            {
                data.map((text,index) =>
                    <Text key={index}>
                    {show ? text : "_ _ _ _ _ _ _ _"}
                    </Text>
                )
            }
        </SafeAreaView>
    )
}

Upvotes: 1

strdr4605
strdr4605

Reputation: 4352

You can't use ul and li in react-native, try FlatList.
You can use useState and conditional rendering.


const data = [
First,
Second,
Third,
Fourth
];

const [show, setShow] = useState(false);


return (
<View>
      <Icon onPress={() => setShow(true)}/>
      <FlatList
        data={data}
        renderItem={({ item }) => <Text> {show ?  item : '_ _ _ _ _ _ _ _'} </Text>}
      />
</View>
)

Upvotes: 0

Related Questions