Trying to use two props in the use defined component

211 Views Asked by At

I am adding two props (textProp & imgProp) to my custom component, but I keep on getting this error JSX expression must have one parent element. This is what I have soo far

function TextImg(textprop, imgprop) {
          return(
              <Text>{textprop.text}</Text>
              <Image source={imgprop.imageUri}></Image>
          );
  }

I tried using div, but this doesn't seem to work. Thanks in advance!

3

There are 3 best solutions below

2
On BEST ANSWER

Wrap this section in a React.Fragment

<React.Fragment>
  <Text>{textprop.text}</Text>
  <Image source={imgprop.imageUri}></Image>
</React.Fragment>

JSX needs a container like this

0
On

There are two problems there:

  1. Your component receives a single argument, which is an object with properties for the props.

  2. Your component must return a single element, single string, undefined or null, or a fragment; it can't return two elements without some kind of wrapper around them.

So:

function TextImg({textprop, imgprop}) {
//               ^−−−−−−−−−−−−−−−−−^−−−−−−−−−−−−−−−− destructuring the object
    return <>
        <Text>{textprop.text}</Text>
        <Image source={imgprop.imageUri}></Image>
    </>;
}

Note the <> and </> denoting the fragment. (You can also use <React.Fragment>...</React.Fragment>.)

Or without destructuring:

function TextImg(props) {
    return <>
        <Text>{props.textprop.text}</Text>
        <Image source={props.imgprop.imageUri}></Image>
    </>;
}
0
On

As others have answered, there are 2 issues going on in your code.

Functional Component is just a function which accepts one parameter which is called props.

But usually to make code easier to read, it was destructured into specific prop properties.

Therefore, instead of

function TextImg(props) {

people write it with

function TextImg({textprop, imgprop}) {

Another one is when returning it needs to be returned one tag to render. Therefore, it can be returned with

return <div>
        <Text>{props.textprop.text}</Text>
        <Image source={props.imgprop.imageUri}></Image>
    </div>;

Instead of div, <></> or <React.Fragment></React.Fragment> can be used to reduce DOM element.