How to extend component functionality in react? - reactjs

Hi I am working on some internal project I need to show case multitennacy concept in React. I have site A and B. A would have all platform components and B will inherit A components and also need to have extended functionality. For e.g A have Carousel component which has own functionality I want to introduce some new features like after first slide move I need to make any call backs etc... In React there conepts of HOC and Composition which will work for extending components as there is no inheritience concept.

Although inheritance in react is not as widely applicable as in other frameworks (and react clearly do not recommend this approach as well), yet there is nothing that prohibits you from using inheritance when necessary:
export class BaseComponent extends React.PureComponent
{
// ...
}
export class AdvancedComponent extends BaseComponent
{
// ...
}
Overriding in descendants required methods.

Related

I can't find extends Component in my Apps.js file after installing React

I followed the installation guide in https://www.w3schools.com/react/react_getstarted.asp to install React on my system. But after installation, I followed their instructions to open the App.js file only to discover that my own Apps.js has
function App() { ... }
while the one shown on w3schools website has
class App extends Component { ... }
Please is there a problem with my installation?
class is just a special function, and extends means it's using other properties of another function.
just change functionApp(){..} to class App extends Component{..}
as well as adding
import React, { Component } from 'react'
to the top of your page and it should work exactly the same.
You need to dig down more to get the exact knowledge of both the Components as both of them are equally important.
Class based components are state based components means you can change the state (data accordingly)
class App extends React.Component{...}
but in functional component,
function App(props) { ... }
you cannot change the data directly here and whatever is coming in props value you can just show that thus it is called stateless component.You should use functional components if you are writing a presentational component which doesn’t have its own state or needs to access a lifecycle hook. Otherwise you can stick to class components
For more: https://medium.com/#Zwenza/functional-vs-class-components-in-react-231e3fbd7108 https://programmingwithmosh.com/react/react-functional-components/
No, there isn't a problem with your installation. React basically has 2 types of Components: Class and Function. The one created using create-react-app is a Function component whereas w3schools uses Class component for most tutorials. You can find more about them here: W3Schools: React Components
Learn about both of them and use whichever you want according to your use case.

React Redux and inheritance

I'm really wondering why there is nothing about Redux and how to deal with inheritance. If I have a base component:
class BaseComponent extends Component{
}
then all other components are extending BaseComponent:
class Todo extends BaseComponent {
}
I want to simply connect the BaseComponent to it's own reducer so every other component which extends it, also can access the same props and states.
Unfortunately can't find any documentation out there. I have no idea if this is a right concept or not.
With react you usually will not further inherit from your own components.
Here is a quote from the official docs on Composition vs Inheritance:
At Facebook, we use React in thousands of components, and we haven’t found any use cases where we would recommend creating component inheritance hierarchies.
Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.
If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.
That being said, if you still want to deviate from the recommended way and have a base component for shared functionality, it is possible. You are still on the "safe side" (i.e. it will most likely not cause too much confusion or trouble) if you (1) reduce the functionality in your base to the least common denominator needed by most of its children (2) do not keep any shared state in your base component (3) do not use arrow functions in your base component and if you (4) make sure to keep your lifecycle methods and connect in your child components to avoid unexpected behaviours.
Performing a connect in your base class, as you are planning to do it, would be problematic as connect returns a newly wrapped component which acts as an owner of your actual BaseComponent (see how connect works). Therefore, you will lose the ability to access your class methods, in your ChildComponents. Also, most likely other bad things will happen because you now independently inject and manage state and lifecycles on two levels (child and base). – Therefore, your best shot, when using a custom BaseComponent, would be to not put connect in your parent but let the child handle the connect.
Here is also a blog article by Dan Abramov worth reading that discusses the question of inheritance in react. His main concerns are that multi-level hierarchies are harder to refactor, name clashes will arise if a parent class later adds methods with names that some child class already uses, sharing logic between child and parent methods makes it harder to understand the code. Overall he suggests to rely on functional programming style.
So what are my recommendations for React components?
You can use class in your JS if you don’t inherit twice and don’t use super.
Prefer to write React components as pure functions when possible.
Use ES6 classes for components if you need the state or lifecycle hooks.
In this case, you may only extend React.Component directly.
Give your feedback to the React team on the functional state proposals.
Generally speaking, whether or not hierarchies are good in OOP programming is a highly debated field.
Inheritance is not widely preferred and encouraged in React and hence you don't find much documentation about this online. A better way to achieve what you want is to export a container which you can then wrap as a HOC to any component you wish to use it for
connectContainer.js
const mapStateToProps = state => {
return {}; // return data you want from reducers
}
const mapDispatchToProps = {}; // define action creators you want to pass here
export default connect(mapStateToProps, mapDispatchToProps);
Now in any component you wish to use the same container properties, you can use them like
import connectHOC from './connectContainer';
class Todo extends React.Component {
}
export connectHOC(Todo);

Can one use reactjs without writing any class?

I am wondering, if classes are just syntax sugar for prototypes, and es6 enhances functional coding, can we write reactJS code purely functionally(and without missing out on lifecycle methods)?
[edit]
Think of the most complex react app, can that be written purely functionally - and would it make sense to do that?
EDIT 2019 May:
React Hooks is here: https://reactjs.org/docs/hooks-reference.html
ES6 classes are syntactic sugar for functions and (with some exceptions) it's possible to rewrite them as functions, this is what transpilers like Babel and TypeScript do.
Since component class inherits from React.Component, it needs to prototypically inherit from it. React.Component doesn't have static properties, so a component doesn't need to inherit them.
This component
class App extends React.Component {
state = { name: 'foo' };
componentDidMount() {
this.setState({ name: 'bar'});
}
render() {
return <p>{this.state.name}</p>;
}
}
becomes
function App(props) {
React.Component.call(this, props);
this.state = { name: 'foo' };
}
App.prototype = Object.create(React.Component.prototype);
App.prototype.constructor = App;
App.prototype.componentDidMount = function () {
this.setState({ name: 'bar'});
};
App.prototype.render = function () {
return React.createElement('p', null, this.state.name);
};
This is what now-deprecated React.createClass originally did, create-react-class helper serves this purpose.
if classes are just syntax sugar for prototypes, and es6 enhances functional coding, can we write reactJS code purely functionally(and without missing out on lifecycle methods)?
We can, but functional component isn't the same thing as a component written with desugared JavaScript class. Functional component is specific React term that refers to stateless functional component. Stateless components don't have a state and lifecycle hooks. It's impossible, or at least impractical, to write real React application with stateless components alone.
Think of the most complex react app, can that be written purely functionally - and would it make sense to do that?
Deliberate avoidance of ES6 class syntax doesn't make sense in general because the lack of syntactic sugar results in verbose and unexpressive code without any benefits. A regular React application still needs to use build step and Babel to transpile JSX syntax because desugared JSX is a hierarchy of verbose React.createElement calls. It is practical only if few React components are used in non-React ES5 application that doesn't need build step to be introduced.
However, this may be possible with third-party libraries, e.g. recompose. It's intended to be used with functional components, e.g. lifecycle helper allows to attach lifecycle hooks to them. Of course, it uses component class internally to do that.
you can use stateless component
This article explain
https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc
example: for stateless component
import React from ‘react’;
const HelloWorld = ({name}) => (
<div>{`Hi ${name}`}</div>
);
export default HelloWorld;
NOTE :
my example lacks lifecycle methods implemented by #estus,so if you don't need those lifecycle methods than you can use below code
Yes you can
import React from ‘react’;
function MyComponent(){
return <div>Hello</div>
}
export default MyComponent;
Live Example
No this is not a way of doing stuff. React gives us two types of components. We use them for a particular purpose.Not everything could be written in stateless components (functions). Stateless components are usually presentation components which only render jsx and have no local state. We can't write methods in stateless components and here comes the Stateful components (class based) where we manage our own state and write methods into it. Further it gives us more control to render our child components. So everything in react follows a pattern and it allows to utilize the power of one way binding.

Properties and states from decorators or parent properties?

I need to know what is most convenient way to implement. In my case, the parent component and the children component are using the same properties and states. My doubt is:
1. Passing the properties from the parent component.
2. Use the decorators to set a properties values in the children component.
advantages and disadvantages of different cases? Thanks!
What you're discovering is the distinction between Components and Containers. Containers are what you refer to as "with decorators" and Components are those without. There is a lot of discussion around best practices on these topics, and those keywords should make it easy to find lots of opinions.
Typically, the standard is that you should prioritize Components over Containers. Components are abstract and reusable if created in the right way. For instance, given your first example, I would modify it slightly to look more like this;
class ComponentParent extends React.Component {
//...
render() {
<ComponentChildren onSomeEvent={this.props.optionActions.anyAction}/>;
}
}
class ComponentChildren extends React.Component {
//...
someMethod() {
this.props.onSomeEvent();
}
}
When written this way, ComponentChildren can now be reused and given a new definition of onSomeEvent to interact with your app in a new way. Building all of your components in this style will eventually lead to a library-like codebase, where code becomes extremely reusable.

do not extend React.Component

the es6 syntax for creating React component is export default class ExampleComponent extends React.Component.However it still work when export default class ExampleComponent without extends React.Component on condition that import React from 'react'; why this happen
It's easy to be in this situation and miss what's happening, but the difference is really huge: without extending React.Component, you're just creating a JS class. Furthermore:
because it satisfies the requirements of a React Class (which you can create with either React.createClass() or as an ES6 class), it'll still "work",
but you won't get lifeCyle methods or access to state (someone correct me if I'm wrong about this, pretty certain you wouldn't with just a class bc there's no backing instance attached).
these "simpler" components are generally faster for React to deal with and require less "machinery", since they're just a (hopefully) pure function that renders something.
so, they key difference here is that with just a class that has a render method you're not "requiring" as much. this should be enough most of the time; you shouldn't need access to state for everything
Hope that helps!
You are creating a "pure" JavaScript class, but once it is not extending a React.Component you will be unable to access specific React behavior. Check how extends work.

Resources