Estoy trabajando en una aplicación React Native donde quiero mostrar una parte de mis elementos solo cuando hago clic en otro elemento.
Lo logré usando const [showSlide, setShowSlide] = useState(false); y luego usando show condicional como {showSlide ? (<View>Element</View>): null}
Funcionó muy bien en mi demostración estática, pero me gustaría tener el mismo resultado usando la función json.map() .
No sé cómo hacer una referencia única al pensamiento que quiero ocultar/mostrar en mi función de mapa.
Hice una demostración aquí para mostrar mis datos dinámicos y estáticos como referencia de lo que quiero hacer: 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> ); }Siempre es una buena práctica separar los componentes en 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> ) }El componente anterior muestra al cliente según sus requisitos.
En el componente de su App , declare
const [show, setShow] = useState({});Aquí almacenaremos booleanos contra el nombre del título.
La función de alternar visible se verá como
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 } }Puede usar el componente Cliente anterior como se muestra a continuación
{ dataC.customer.map((customer)=>( <Customer customer={customer} titleVisible={show[customer.name]} toggleVisible={toggleVisible}/> ))}