Reusable components structure (react native) - reactjs

I want to seek advice regarding reusable components structure in react-native. I wanted to make them lean and adaptive. What I thought was to have generic components as wrappers and then have specific components using those wrappers. e.g. For products carousel I pass products data to Carousel component (just a FlatList) that renders Card component multiple times that has products details and product related icons. But what If I want to have categories or anything else inside card?
What I thought is to make card content passed as props
<Carousel>
{.... // ProductContent}
</Carousel>
<Carousel>
{.... // CategoriesContent}
</Carousel>
But it seems like I am over complicating things as I'll pass data to carousel, then carousel will pass it to card then card will pass it back to my content and carousel is mere a Flatlist and card is mere a TouchableOpacity. And also it will not look clean as I will have to define the content wherever I am using the Carousel. Why not just create two separate carousel components
<ProductCarousel />
<CategoriesCarousel />
Similarly I have a <PopUpModal /> component. which I am using for showing product details. Should I pass product content as children to keep content generic or just create <ProductDetailModal /> as a component and create more modals if required
So the point is whether to have specific bits and pieces of the app as components so that connecting them will complete the puzzle or to have generic customizable wrappers like components. Or something in between

I recommend atomic design.
Its hard to explain it here, so Ill leave a link.
https://bradfrost.com/blog/post/atomic-web-design/
The key point is to break(modularize) everything into tiny, replacable & reusable bits, and actually reusing and replacing them.
Another important, yet often neglected point is that separating smart and dumb components.
https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
This is surely neglected and also seems cumbersome to aplly, but will simplify the codebase by detaching view related logic to data(api) related logic.
So those are the two rules I try to stick to.
P.S. Just as im_baby has pointed out in the comments, there is no answer, and we all compromise at some point. So try to be long sighted and practical, dont be dogmastic to rules, neither be short sighted and mess up the overall code quality and structure for immediate comfort

You will make a component like this giving the parent component all the liberty to change it through props.
render() {
const { all the props that you want to give your component} = this.props;
return (
<Carousel>
{this.props.childern} // like this you can design your one carosal and cahnge the data/view in the carosal.
</Carousel>
);
}
Then in your parent component you need to import this component like this:
import CarouselComponent from '../CarouselComponent'; //path to your component
<Carousel>
<View>
//any view you want to be rendered in the modal
</View>
</Carousel>

Related

I am confuse reactjs component design

How do I or what is the alternative method to break this layout into react component? The code below is bootstrap 4 for simplicity and what I want to achieve is something like this https://codedthemes.com/demos/admin-templates/material-able/bootstrap/default/ where contents are dynamic which is actually consist of different components. So what I am showing here is the simplified HTML code of the actual thing but has a similar structure. The question here how do I break them into components with this HTML structure? Many thanks in advance and appreciate any helps. Thanks again.
<div class="wholepage">
<navbar>
</navbar>
<sidebar>
<dynamiccontent>
</dynamiccontent>
<sidebar>
</div>
What you are describing is one of the selling points of React - the ability to modularise bits of code into what React calls components.
To build something like what you have linked you would need to nest components.
Using the example you might have an app.js that looks something like this.
import React from 'react'
import graph1 from './components/graph1'
import graph2 from './components/graph2'
const app = () => {
return (
<div>
<graph1 key1="props data goes here"/>
<graph2 key1="props data goes here"/>
</div>
)
}
export default app;
graph1 and graph2 are seperate components that have been imported and then nested in the app component as shown below.
The key1 attributes in each component accept values/functions that are passed down to graph1 and graph2 components for further processing and/or display. This is what allows you to make the content dynamic.
What I've mentioned above is very rudimentary but I think answers your question. ReactJS is a massive topic and will take a lot of practice to get used to. is well documented and there is a lot of fantastic documentation, examples and discussion online such as:
React components
React Props
React Design Patterns
DISCLAIMER: Fairly new to react myself, just trying to share the knowledge :)

declarative composition vs imperative in react js

While designing the application in react js to increase the reusability I have used the Tabs and then passed the tabs and headers something like this
const tabs ={
"tabHeader1": TabContent1,
"tabHeader2": TabContent2
}
<SwipableTabs tabs={tabs} />
Now my confusion arose when I had to render them permission based , In order to avoid if else juggling I have designed a component like below :
<ProtectedAction>
{children}
</ProtectedAction>
my ProtectedAction component will check for permission and will render the children based on that. Which is exactly what react suggest(be declarative).
Now when I see the above example like tabs which is data driven I am forced to use if else again which I wanted to get rid of.
Please suggest if any better approach is possible .

Real-Time use case of this.props.children

I have read many articles to find out the real time use case of this.props.children but i didn't find the answer that i am looking for.I know that this.props.children is used to access the data b/w the opening and closing tag of a component. But my question is why can't we add a prop to the component instead of writing data b/w opening and closing tag.
for Ex:
<Example>This is data<Example> //can be accessed as this.props.children
can be written as
<Example data="This is data"/> //can be accessed as this.props.data
Can somebody please explain me with a real-time example of where we can achieve a certain task by using only this.props.children?
For example if you have complicated children of a component:
<Card>
<div class='title'>Title</div>
<div class='content'>Content</div>
</Card>
It would be easier than if you write like:
<Card content={[<div class='title'>Title</div>, <....>]} />
Samething you can find here, for example in Drawer component of Material-UI here. Drawer is a component that slides from the left, it can contain anything, so using props.childrens.
While making an app, you want a parent component which will render anything in your component. The use cases which I can think of are:
When you want to open a different component depending upon the route change.
const App = ({ children }) => (
<div className="full-height">
{children}
</div>
);
When you want to have same styles throughout your app for generic elements such as body, head etc. You'll just have to apply on this component, e.g., in above example, the full-height will get applied everywhere in the app on top component. (Obviously there are other work arounds but this is always more clear)
For use cases where you want to expose your component (when component doesn't know children ahead of time) as libraries and props can vary a lot and complicates the rendering. Read this
Obviously you don't have to use it but it makes code more elegant and understandable.

Passing components as props? Compositional vs Higher Order Components

I'm creating some layout-level components for my React app. As I understand it there are two main design patterns I can utilize - compositional, and higher-order components.
Am I correct in thinking that I have to make use of props.children when I want to create a wrapper component in the compositional style?
And am I correct in thinking that if I want to, say, pass in two different components (as in the Higher-Order Components example below), I have to make use of the higher-order component style?
Compositional:
const CenteredColumn = props => (
<div className="columns">
<div className="column is-8 is-offset-2">{props.children}</div>
</div>
);
Higher Order Component:
const withTwoColumns = ({ first, second }) => (
<div className="columns">
<div className="column">{first}</div>
<div className="column">{second}</div>
</div>
);
Yes you are right. The compositional style allows you to pass children to components ahead of time before they are aware that they have them. So we could do this:
Please see: https://facebook.github.io/react/docs/composition-vs-inheritance.html
So to the h1 and p tags, the div with a className of 'fancyborder' will cover/wrap/surround them.
Regarding HOCS, you are also correct. They are components they receive other component(s) as inputs and render component(s) as the output.
Pardon me not providing code. I used a touch device. Hope this helped.
Both work. From the way you're writing it, it's a coding style/hierarchical choice. There are anti-patterns for React, but this is not one of them.
The way you should you set your layout is by dividing your workflow or proyect structure in presentatational ( Stateless) components and Container components.. The presentationals components will only receive props from their main components while the container components will contain the logic of the applications.

How to call method on a JSX element when writing functional react

I have recently started using React and Redux. One thing that often messes with my brain is how to re-write all the code examples from documentations that are usually written object based to my functional code base.
I am now in one of those situations; I can not find a way to call a method belonging to react-custom-scrollbars (link to docs) which I am using in one of my components. Below is a simplified version of the component. I have commented out the section where I would like to call the method scrollToBottom().
Bonus question: If I skip using the onUpdate() event, how would I go proceed if I want to call scrollToBottom() when a message is appended to the messages array?
const Chat = ({messages, app, keyDown, pressSend, setMessage, toggleEnter}) => {
return (
<div id="orbit-chat-content">
<Scrollbars
onUpdate={() => {
//
// HERE I WANT TO SCROLL TO BOTTOM
//
// this.scrollToBottom()
//
}}
className="react-scrollbar">
<div id="orbit-chat-conversation">
{ messages.map(message => <Message {...message} />) }
</div>
</Scrollbars>
</div>
);
};
export default Chat;
Thank you very much for taking your time to look at this!
The answer to your question:
Stateless components don't have refs. Which you would normally use to access the scrollbars instance.
Your real problem:
...how to re-write all the
code examples from documentations that are usually written object
based to my functional code base.
You don't have to. Statefull components are not deprecated or so. They are the base. PureRender Components / Functional components, are just an addition to the stack to provide a way of writing small independent components, like a Button.
Of course you can write a whole app only with stateless components, but if you need internal state, access to instances, some internal logic, you can and should use Normal Components too.

Resources