user55093
user55093

Reputation: 103

Display react-native components array

I have an array of react native components and would like to display them all at once in a View however I keep getting the error

RawText [object object] must be wrapped in an explicit Component

and displaying it in a Text will not get the desired result, how do I go about it.

render()
{
var CompArray = new Array();
CompArray[0] = <TextInput placeholder="First Name"/>
CompArray[1] = <TextInput placeholder="Last Name"/>

var Components = CompArray.join();

return(<View>{Components}</View>);
}

Upvotes: 9

Views: 34393

Answers (2)

Gui Herzog
Gui Herzog

Reputation: 5615

One great way of creating an array of components is creating an array of data and using a map to transform them into components. This also avoids duplicating code.

To do this is easy:

    const form = ['First Name', 'Last Name', 'Phone', 'Email', 'Etc']
    const textInputComponents = form.map(type => <TextInput placeholder={type} />)

Them on render or return: call the array of components you just created:

    render(){
        <>{textInputComponents}</>
    }

This is especially useful if your form/array is big, and you can even use it with an array of objects.

Upvotes: 24

Praveena
Praveena

Reputation: 6941

Your code is fine but you are doing one extra thing which is joining the array. You don't have to do that.

render()
{
 var CompArray = new Array();
 CompArray[0] = <TextInput placeholder="First Name"/>
 CompArray[1] = <TextInput placeholder="Last Name"/>
 return(<View>{CompArray}</View>);
 }

Upvotes: 5

Related Questions