9

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>);
}

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what the meaning of type here ? const textInputComponents = form.map((type)=> <TextInput placeholder={type} />) can i use any word instead ?
Yeah, absolutely. The type here means the type of the TextInput. But you choose whatever you want.
5

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>);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.