Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js combining static elements

Tags:

reactjs

I want to dynamically combine different react elements:

const Addresses = () => {
  const addressElement = () => {
    return  <TextInput
      name="addressLine"
     />;
  };
  const addressElement2 = () => {
    return  <TextInput
      name="addressLine2"
     />;
  };
  let address = addressElement1 + addressElement2;
  return (
    <div>
      address
    </div>);
};

Instead of printing the elements this is printing:

[object Object][object Object];
like image 639
Potney Switters Avatar asked Oct 28 '25 09:10

Potney Switters


2 Answers

Here's what you want to do:

return (
  <div>
    { addressElement1() }
    { addressElement2() }
  </div>
);

or you can make them into an array beforehand:

const address = [ addressElement1(), addressElement2() ];
return (
  <div>
    { address }
  </div>
);
like image 153
Yuya Avatar answered Oct 31 '25 01:10

Yuya


Hmm there some little mistakes on your implementation. If you want to render variable you need to use {address}. And combining React component can be made with simply [, ]

Your final code would be like this

let address = [<addressElement1/>, <addressElement2/>]
return (  
    <div>
        {address}
    </div>
);

edit

let address = [<AddressElement1 key="left"/>, <AddressElement2 key="right"/>]

But you must rename your stateless component width A instead of a

If you don't want to use key you can directly

return (
    <div>
      <AddressElement1/>
      <AddressElement2/>
    </div>
);
like image 43
Michael Rasoahaingo Avatar answered Oct 31 '25 00:10

Michael Rasoahaingo