Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing component into a variable and reuse it

Ok i got components imported as

import Payment from './pages/payment';
import Chat from './pages/chat';

Now I am using Drawer component and using it together with Navigator my renderScene become something like this

if( route.id == 'payment'){
    return  <Drawer  xx={} yy={} and a lot more >
              <Payment navigator={navigator} />
            </Drawer>
}

if(route.id == 'chat'){
    return <Drawer  xx={} yy={} and a lot more >
              <Chat navigator={navigator} />
            </Drawer>
}

Those lengthy Drawer code are being used again and again. I want to store that <Payment navigator={navigator} > or the other into a variable and then return that with Drawer only once.

How can i store it and return it with Drawer?

Thanks

like image 607
cjmling Avatar asked Aug 22 '16 09:08

cjmling


2 Answers

Not sure if you are asking this but what about something like:

const routes = {
 payment: Payment,
 chat: Chat
 ...
}

And then, just:

const Scene = routes[route.id];
return (
  <Drawer>
    <Scene navigator={navigator}/>
  </Drawer>
)
like image 200
Ferran Negre Avatar answered Oct 19 '22 01:10

Ferran Negre


Here you have 3 options:

// 1. Group the drawer props in an object
const drawerProps = {
  xx: ...,
  yy: ...
};
<Drawer {...drawerProps}>
  <Chat navigator={navigator} />    
</Drawer>

// 2. Define a wrapper object that populates the common Drawer props
const CustomDrawer = ({ children }) => (
  <Drawer  xx={} yy={} and a lot more>
    {children}
  </Drawer>
);


// 3. Define a wrapper object that populates the common Drawer props with default props. (Can be 
// overriden.)
const CustomDrawer = ({ 
  xx='XX',
  yy='YY',
  children 
}) => (
  <Drawer  xx={xx} yy={yy} and a lot more>
    {children}
  </Drawer>
);

EDIT: I missunderstood your question, for storing the inner part you just have to assign it to a varible and use it.

const routes = {
  chat: <Chat navigator={navigator} />,
  payment: <Payment navigator={navigator} />,  
}


<Drawer {...drawerProps}>
  { routes[route.id] }
</Drawer>
like image 27
Manolo Santos Avatar answered Oct 19 '22 02:10

Manolo Santos