Is there any harm in making everything a component? - reactjs

Even if it's not reusable? I am having difficulty understanding what should be a component and what shouldn't. So, I was thinking maybe making everything a component. For example, a <img /> tag wrapped in <NavBarImage /> Component?

You would like to break some part into new component to make it reusable to other components or when your component has such high complexity(doing many things different) that it makes more sense to break down into smaller components.
you are talking about the first scenario. create some atomic component like a img tag. that's perfect acceptable to create a design system for your project to reuse through your project. Like, you can have a Typography element, you may define some basic custom props that can change how it looks and consume in different components.
now, if you want to create such a specific component that's not reusable I don't see the point. you are creating two or three files ( NavBarImage.js, NavBarImage.css, NavBarImage.spec.js), then you have to import it to NavBar. it wouldn't serve the purpose to make it reusable, and in a large project you'll face yourself lost in a sea of pointless components.

Related

Create React Component that looks similar to existing Component

I have a Card component. I want to create a Component that is similar in appearance with small differences.
it will likely have additional/ different functionality (event handlers etc)
What is the best way to architect this? Do i just create a new component or are there better strategies?
Thanks
Think of the component itself as a blueprint (I hesitate using "class" here because JavaScript). When you mount the component inside your render function, or in the case of functional components your returned component, you are "instantiating" that blueprint/class.
So for your example, you have a <Card onPress={someEventHandler} style={somestyle}/>.
You want another <Card /> component with different style and handler? Just instantiate it again:
<Card onPress={someOtherEventHandler} style={someOtherStyle} />
Maybe you want another <Card /> component with same style, but different handler? Easy:
<Card onPress={someOtherEventHandler} style={someStyle} />
Similar to instantiating objects in standard OOP, there is no right or wrong answer to this. If you need a card for each element in an array, use a map:
{someArrayOfCards.map(card => <Card onPress={someEventHandler} style={someStyle}/>)}
Hope that answers your question.
EDIT: Another important thing to understand is that each component represents a node on the VDOM/DOM. The reason it actually doesn't matter which architecture is used to instantiate each component is because you're creating a separate node regardless.
If they are very minor differences, pass a prop into the Card Component, and have an if statement in there that results in different functionality.
However, if the functionality is different (different state, events etc), then duplicating the component and changing it can often be the cleaner solution.
As ever with deciding on architecture, both are valid, and it really depends on how large the differences are, and how (in the future) each of the components are likely to change.

What is proper or effective way for Composition of React Component?

I have multiple view in my application, I need helpl in how to use reusable component effectively ? Is it ohk if I create viewspecific component from reusable component ? - Generic Tree View . For users View which will render with user specific data and actions .
I have written re useable component in my react app.Which I have to use it with different data and action is it ohk to creat new component which use resuable component and provide data related to that ?
i.e
Component - DepartmentTree which renders and some functions related to Department. So finaly I will render
Component - usersTree same way here it calls and methods related to users . In the users view I will render
It's definitely OK to create a view-specific component that renders a reusable component. You could let this depend on how big your page is. If it includes a lot of components, then do split them up in view specific components.
About the data, you have a few options... First of all you could map the data response to a general structure that your TreeView component can read, so you only need to pass some props to the TreeView component. You could do this in the redux reducer.
If you require specific data different behaviour, but you still want to use the reusable TreeView component, you could think about creating a Higher Order Component. This component will wrap your reusable component and add some specific logic to it. You can read about it and see some good examples here: https://reactjs.org/docs/higher-order-components.html
The most important thing I always keep in mind: It's not always about how you finally do it, it's about keeping it simple, understandable and consistent.

Where to write logic related to component that doesn't affect the UI directly

I have a component which contains a textarea. Whenever I enter text I run a set of validations against the text and depending upon results I update the UI. You can assume the code to be like this:
onTextChange(e) {
const results = this.runValidations(e.target.value)
}
Now, the problem is this.runValidations is like 100 lines of code sitting right there in the component but doesn't affect the UI directly and is specific only to the component and its child components. But, it makes my component file bloated.
So, is there any convention that other people follow in their React-Redux apps to handle such logical code that is specific to the component but is not part of the UI logic? Where do they place such code?
At the end of the day, most business logic doesn't have a lot to do with React/Redux - so they can usually be shovelled out into their own utility functions or classes. Which is great for a few reasons
a) easier to test because it hasn't zero linkage to React/Redux and
b) keeps your actions light, and
c) more encapsulated - having minimal knowledge of react/redux is not a bad thing.
It's all just Javascript - there is nothing wrong with importing custom business classes or utility functions.
Edit
My folder structure will typically look like:
my-component
child-components
Child1.js
_Child1.scss
Child2.js
_Child2.scss
helpers
util1.js // with a single default export
util2.js // with a single default export
_MyComponent.scss
MyComponent.js
MyComponent.spec
Where child components are (or should) only be pulled into this component. Ie. they shouldn't be used by other components.
This hashnode article also has a great structure if you are using redux as well: hashnode.com/post/tips-for-a-better-redux-architecture-lessons-for-enterprise-scale-civrlqhuy0keqc6539boivk2f
It seems that you are missing the concept of components vs containers (or dumb components vs smart components, as some like to name it). Basically, it is a good practice to apart your business logic from you pure presentational components.
Have a look at Presentational and Container Components, by Dan Abramov.

How to handle layout containers which do not match component hierarchy?

As far as I've understood, in React, components should communicate in an hierarchical order through the nested hierarchy. Given this, how should it be handled when an application's layout container structure don't match the natural/expected/logical component hierarchy.
As an example of my question, I've come up with a scenario based on my app, that I'm not sure how to implement properly:
The screen is split vertically in two halves. This is done having two
div containers side by side. To each halve there's a corresponding
component: ItemsList and ItemDetails.
Nested inside ItemsList, there are several Item components we can
click on.
Each time there is click on an Item, the corresponding defined _itemID prop value needs to be sent to ItemDetails so it can load and display Item details in there.
The problem is, given the component structure, how can ItemDetails be a child of Item and still be on the right section of the screen where it's intended to be. (At least without some weird CSS which I want to avoid).
Here's the layout:
<div className="wrapper">
<div className="itemList" style="width:50%; display:inline-block;">
<div className="item">item1</div>
<div className="item">item1</div>
<div className="item">item1</div>
</div>
<div className="itemDetails" style="width:50%; display:inline-block;">
The details of the selected item.
</div>
</div>
I believe I could send information from a child to parent following up the hierarchy, but this don't seem practical. Considering this scenario is just a simplification of my actual problem (I have a lot more nested components), I believe this would make the code messy and confuse.
Is there a clean, simple way to achieve this in React? Am I missing some concept?
If it were me I would have a container component based off your wrapper. It would handle all state changes and be the source of truth for what the currently selected item is. Then you'd just need to pass a callback from the wrapper component through props down to your ItemsList that would handle setting the state of the active item.
Then you can just pass activeItem as a prop to the itemDetails component. It is a fairly common pattern to have a container component that manages state and passes callback functions down to child components that would allow them to create an action that changes the state of the container
The heirarchy would look like:
<Wrapper> // holds the state of active item and provides functions to change the active item
<ItemList /> // provides a list of items that when clicked sets active
<ItemDetail /> // shows the detail of the currently select item
</Wrapper>
Here is a pen of what i'm trying to explain
http://codepen.io/finalfreq/pen/KgEzgE
This always depends on many things. If you intend for a small project you are fine working with setState and refer to finalfreq's great answer. If you intend to scale well (aka grow without pain) then I would opt for a state management library.
I hate to be the guy who answers a simple question with "Use ... library! It's awesome!", and like I said, it really does not get much better than finalFreq's answer if you don't have the need to grow your app. A redux author even mentions that you should learn react without redux first, and you should not reach for it until you have a real need.
If you use redux then you should never have to worry about component structure for the sake of passing scope. Component structure if I am not mistaken(which I often am XD) should be based on what is easiest to understand and maintain, also performance comes to mind.
Your question is in the context of react, but I think this is really a state management and data communication question. I opt for redux.js lately(a pub/sub like library), but there are many alternatives. Redux requires a bit more typing, but offers extreme explicitness that you may appreciate as the project grows.
But the main reason I would reach for this is that it focuses on functional programming principles, and pushes your state mutations to the outer fringes of your app. This simplifies your code. If there is a bug it's easy to find(All mutations should be in the reducer files. You would also move your calculations to a util file which simplifies your code even more)
http://redux.js.org/

ReactJS Modal Component

How do you create a ReactJS component that reaches multiple levels up the component/DOM hierarchy?
A good example of this is a Modal. I want to trigger and control the modal from a child nested way down in my app, but a Modal requires that the DOM be much higher, most likely all the way up as a child of the document body.
I'm considering a "portal" pattern, as described here: https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md#portals
FakeRainBrigand even wraps the pattern up nicely in a mixing in this post: https://stackoverflow.com/a/26789089/586181
This feels like a hack to me. Great if you want to use a non-react library like jquery-ui, but without that need breaking out of react just to render a react component somewhere else in the DOM seems like overkill. Is there a more "React" way of achieving this?
Thanks
I'll leave this best to the react documentation. If you must have buried React elements that need to communicate with other elements outside of their Parent Child or possibly even grandparent than see the below.
For communication between two components that don't have a
parent-child relationship, you can set up your own global event
system. Subscribe to events in componentDidMount(), unsubscribe in
componentWillUnmount(), and call setState() when you receive an event.
https://facebook.github.io/react/tips/communicate-between-components.html
I've written a library to help with this. I avoid the DOM insertion hacks used by Portal strategies out there and instead make use of context based registries to pass along components from a source to a target.
My implementation makes use of the standard React render cycles. The components that you teleport/inject/transport don't cause a double render cycle on the target - everything happens synchronously.
The API is also structured in a manner to discourage the use of magic strings in your code to define the source/target. Instead you are required to explicitly create and decorate components that will be used as the target (Injectable) and the source (Injector). As this sort of thing is generally considered quite magical I think explicit Component representation (requiring direct imports and usage) may help alleviate confusion on where a Component is being injected.
You can completely use my library to bind a ModalComponent to a root level component that you decorate with the Injectable helper. I plan on adding an example of this use case soon. It even supports natural props pass throughs, and all the various component types i.e. stateless/class.
See https://github.com/ctrlplusb/react-injectables for more info.

Resources