skip to Main Content

My use case:
I’m trying to create a button component, so the children of the component are of ReactNode type, usually string but it could be anything.

Then in my Button component, when I render the children, I wrap them in <Text> in case they’re a string, but if they’re not if they are for example a bunch of <View> since they’re nested inside <Text>, they’ll appear in one line

My question:
If I have for example

  <Text>
    <View>
      <Text>Hello</Text>
    </View>
    <View>
      <Text>There</Text>
    </View>
  </Text>

How can I have the Hello and There appear on two different lines?

2

Answers


  1. You can use the {'n'} newline character between them ?

    <Text>
      <View>
        <Text>Hello</Text>
      </View>
      {'n'}
      <View>
        <Text>There</Text>
      </View>
    </Text>
    

    To answer the comment:

    Not directly, but with a tricky way, something like this, mapping through the elements wrapped within the button i.e children and apply the disred styling to their wrapper View component, since children can be of different node types so we use the View as a container and style it :

    const Button = ({ children }) => {
    return (
     <View style={{...}}> 
      {Array.isArray(children) ? (
            children.map((child, index) => (
              <View key={index} style={{...}}>
                {child}
              </View>
            ))
       ) : (
            <Text style={{...}}>{children}</Text>
       )}
     </View>
    );
    }
    
    Login or Signup to reply.
  2. You can have both Text field inside a same View without wrapping them in separate Views like below,

    <View>
      <Text>Hello</Text>
      <Text>There</Text>
    </View>

    And it will appear in different lines.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search