Butri
Butri

Reputation: 457

Rendering a comma separated string of values in React Native

I am extracting {item.dosage} from a JSON which gives me the following string

"300gr short pasta, 2 spring onions, 50gr parmesan cheese"

and I'd like to show it each ingredient separated by comma in a separate text line like this

   300gr short pasta
   2 spring onions
   50gr parmesan cheese

I was trying to do the following within my JSX

{item.dosage.map((step, i) => (
        <Text>
            {i > 0 && ", "}
               {step}
        </Text>
 ))}

and I'm getting an error about "undefined is not a function...".

Upvotes: 4

Views: 10394

Answers (2)

adir abargil
adir abargil

Reputation: 5745

in the first sight, it looks like that is getting close to what u look for this way u can give margins to the View as desired..

{item.dosage.split(', ').map((step, i) => (
  <View>
      <Text>
        {i > 0 && ", "}

         {step}
      </Text>
  </View>
 ))}

Upvotes: 2

Liu Lei
Liu Lei

Reputation: 1297

const str = "300gr short pasta, 2 spring onions, 50gr parmesan cheese"

...
<Text>
  {str.split(',').map((step)=> <Text>{step}{",\n"}</Text>)}
</Text>
...

// so try this way
<Text>
 {item.dosage.split(',').map((step)=> <Text>{step}{",\n"}</Text>)}
</Text>

Upvotes: 4

Related Questions