Search code examples
react-nativestyled-components

Separate text-styling with styled components in React native


Im doing an app using react-native and styled components where I want to make the text visible over an under an image. The code fot my return looks like this:

return(
     <Container>
     <TouchableOpacity onPress={fetchDogPhotos}> 
     <Text>Tap the screen for new dog</Text>
      <View>
         {photos.map((photo) => (
           <View key={photo.id}>
           <Image
             resizeMode="contain"
             source={{uri: photo.url}}
             style={{width: 300, height: 600}} 
             />  
             <Text>{photo.breeds[0].name}</Text>
             <Text>{photo.breeds[0].temperament}</Text> 
          </View>
         ))}
      </View> 
      </TouchableOpacity>    
    </Container>
    );

I want to be able to style the Tap the screen for new dog and the {photo.breeds[0].name}{photo.breeds[0].temperament} but I want to style them separetly.

Now my styling looks like this (wisch targets both text areas)

const Container = styled.View`
  flex: 1;
  background-color: white;
  align-items: center;
  justify-content: center;
  text-align: center;
`

Does anyone know how to I can write the code so that it creates some sort of "className" or other identifyer for the different text part so that I can target the texts separetly? And also hoe to write that correctly in styled components? :)

Thanks in advance!


Solution

  • You can style every Text separetly

    const TapText= styled.text`
     ...style
    `
    
    const NameText= styled.text`
     ...style
    `
    
    const TemperamentText= styled.text`
     ...style
    `
    
    <Container>
     <TouchableOpacity onPress={fetchDogPhotos}> 
     <TapText>Tap the screen for new dog</TapText>
      <View>
         {photos.map((photo) => (
           <View key={photo.id}>
           <Image
             resizeMode="contain"
             source={{uri: photo.url}}
             style={{width: 300, height: 600}} 
             />  
             <NameText>{photo.breeds[0].name}</NameText>
             <TemperamentText>{photo.breeds[0].temperament}</TemperamentText> 
          </View>
         ))}
      </View> 
      </TouchableOpacity>    
    </Container>