0

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!

Isha
  • 138
  • 1
  • 10
  • You must only ever return _one_ react element. Consider wrapping Text and Image in a Fragment? https://reactjs.org/docs/fragments.html – evolutionxbox Oct 03 '20 at 16:03
  • Does this answer your question? [React - expressions must have one parent element?](https://stackoverflow.com/questions/48886726/react-expressions-must-have-one-parent-element) – evolutionxbox Oct 03 '20 at 16:04
  • Whoever voted your question down should undo that. Welcome to SO. – Daniel Oct 03 '20 at 16:40

3 Answers3

1

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

Daniel
  • 4,816
  • 3
  • 27
  • 31
1

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>
    </>;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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.

Kevin Moe Myint Myat
  • 1,916
  • 1
  • 10
  • 19