I'm working on an React Native application where I want to display some part of my elements only when I click another element.
I achieved that using const [showSlide, setShowSlide] = useState(false); and then using conditionnal show like {showSlide ? (<View>Element</View>): null}
It work very good in my static demo but I would like to have the same result using json.map() function.
I don't figure how to make an unique reference to the think I want to hide/show in my map function.
I made a demo here to show my dynamic data and the static one as a reference of what I want to do : https://snack.expo.dev/@37creaorganization/json-data---clickable
export default function App() {
const [showSlide, setShowSlide] = useState(false);
return (
<View style={styles.container}>
{/* STATIC EXAMPLE */}
<TouchableOpacity onPress={() => {setShowSlide(!showSlide)}}>
<Text style={styles.paragraph}>
{dataC.customer[0].name}
</Text>
{showSlide ? (
<View>
<Text>{dataC.customer[0].requests[0].title}</Text>
</View>
) : null}
</TouchableOpacity>
{/* END OF STATIC EXAMPLE */}
<View style={{width:"100%", height:5, backgroundColor:"red", marginTop: 10, marginBottom: 10}}></View>
<Text style={{textAlign: "center"}}>DYNAMIC EXAMPLE</Text>
{/* DYNAMIC DATA */}
{ dataC.customer.map((customer)=>(
<TouchableOpacity onPress={() => {setShowSlide(!showSlide)}}>
<Text style={styles.paragraph}>
{customer.name}
</Text>
<View>
<Text>{customer.requests[0].title} </Text>
</View>
</TouchableOpacity>
))}
{/* END OF DYNAMIC DATA*/}
</View>
);
}
Its always best practice to separate component in React
const Customer = ({customer, titleVisible=false, toggleVisible})=>{
const onToggleVisible = ()=>toggleVisible && toggleVisible(customer.name);
return (
<TouchableOpacity onPress={onToggleVisible}>
<Text style={styles.paragraph}>
{customer.name}
</Text>
{titleVisible && <View>
<Text>{customer.requests[0].title} </Text>
</View>}
</TouchableOpacity>
)
}
Above component displays customer as per your requirement.
In your App component declare
const [show, setShow] = useState({});
Here we will store boolean agains title name.
Toggle visible function will look like
const toggleVisible = (name)=>{
if(show[name]){
setShow({...show, [name]:false}) //Updating it to false as its already visible
} else {
setShow({...show, [name]:true}) //Its not visible so let's make it visible
}
}
You can use above Customer component as below
{ dataC.customer.map((customer)=>(
<Customer customer={customer} titleVisible={show[customer.name]} toggleVisible={toggleVisible}/>
))}