Uladz Kha
Uladz Kha

Reputation: 2364

How to generate <Text /> component in loop using react native?

I would like to know how can I can generate components from a variable which stores an array of strings, with a loop (or something similar). For example, I have an array:

const arr = ['Hello', 'Awesome', 'Stack','Over','Flow', 'Have', 'A', 'Nice', 'Day'];

and I wrote this method:

function renderT() {
  return arr.map(obj => {
    <Text>{obj}</Text>;
  });
}

and I then call it in the return statement of my render() method:

return (
  <View style={styles.row}>{renderT()}</View>
)

As result I don't have any error or text on the screen. I tried to use different kind of loop for, forEach, map and it didn't work. Could you please point me or suggest me the right way how can I implement it?

Upvotes: 2

Views: 2791

Answers (3)

Dacre Denny
Dacre Denny

Reputation: 30360

There are some a subtleties to be aware of that if missed, will be causing errors and/or unexpected behaviour. Consider the following adjustments to your code, which should address the run-time errors:

function renderT() {

  // Ensure arr is defined in scope of, or is "visible" to, renderT()
  const arr = ['Hello', 'Awesome', 'Stack','Over','Flow', 'Have', 'A', 'Nice', 'Day'];

  return arr.map((obj, index) => {
    // Compose a unique key for the text element. A unique key is need when 
    // rendering lists of components
    const key = index;

    // Add return to ensure the text element is returned from map callback
    return <Text key={key}>{obj}</Text>;
  });
}

Something to be aware of is the key prop - this should be supplied for components that are rendered in a list (ie, <Text> in your case).

The reason for the key prop being needed is detailed here. Each key per item rendered must be unique - generally you should avoid using the index of a mapping callback, however seeing the uniqueness of values in arr cannot be guaranteed, it would be necessary.

Hope that helps!

Upvotes: 2

Orlyyn
Orlyyn

Reputation: 2606

Your map function on your arr is not returning anything, that's why you're not visioning any texts.

Try to replace your function renderT() by:

function renderT() {
  return arr.map(obj => (<Text>{obj}</Text>));
}

(just replace the {} around your <Text /> value by ())

Upvotes: 1

Simon
Simon

Reputation: 6462

You should replace

function renderT() {
  return arr.map(obj => {
    <Text>{obj}</Text>;
  });
}

by this:

function renderT(arr) {
  return arr.map(obj => {
    return <Text>{obj}</Text>;
  });
}

and this:

return (
  <View style={styles.row}>{renderT()}</View>
)

by this:

return (
  <View style={styles.row}>{renderT(arr)}</View>
)

The two errors were the missing return and the missing argument in your function renderT. Then you have to call your function with the right argument (your array).

Upvotes: 1

Related Questions