Making a function component from a class component. What is props here? - reactjs

I was trying to implement a drag and drop functionality to my ant design tabs component. The example they mentioned in the documentation is class based. I was trying to make it into function component but I am not sure what props are in this case.
Ant design demo
Official documentation
For example, I got confused here, this class component itself is outside another class component. How would react extract these connectDragSource, connectDropTarget, children when it has noting that is being passed from the props? And how would I extract these when I am in a function component?
class TabNode extends React.Component {
render() {
const { connectDragSource, connectDropTarget, children } = this.props;
return connectDragSource(connectDropTarget(children));
}
}
and there are some other aspects in the provided demo that are confusing to me. It would be great help if you could breakdown and explain what is happening so that I can turn this into a react functional component.

In functional component you can access props as one of your component's argument, and also instead of returning your JSX by render method, whatever you returns by your functional component, considers as your JSX output, like this:
function MyComp(props){
// do whatever you want by props (actually body of your function is equivalent to render method in class component)
return (<div>...</div>);
}
Here I implemented your tab example by function component.

Related

How to use useIntercom() from react-use-intercom in class component?

I am using react-use-intercom.
Using following hook from the guide react-use-intercom which suggests to use functional components everywhere.
const { boot, shutdown, hide, show, update } = useIntercom();
However I am using class components everywhere, is there any way that I can do use it in class component itself, because the official documentation has examples in functional component only.
I want to use this methods on click of a button, i.e on some events.
You cannot use hooks in class component, which is a rule from React. There is a way to get pass that. You can create a functional component with useIntercom, pass the state or function as props to your class component. For example:
function Intercom(){
const intercom = useIntercom();
return <YourComponent {...intercom} />
}
For example, you now can use the boot function in your component like
this.props.boot()

What is the difference between Props in Class and functional components in ReactJs?

I came across this Article
https://overreacted.io/how-are-function-components-different-from-classes/
It's very interesting but there is one thing I wanted to ask, I kinda understand it but wanna dig more by exploring some more articles on this topic, particularly, what does it mean that props are tied to "this"?
Does the difference come from how the closures work ? It's kinda vague I think I don't quite understand how render method works and how the variables are being stacked while calling a method in a class...
Can anybody help me find more articles on this issue ?
Thanks
You must note that classes are instantiated while Functional components are executed.
Now when instantiating a class, React takes in the attributes i.e props attached to each instance of the Component and sets it as a class Property within React.Component kind of like
class React.Component {
constructor(props) {
this.props = props;
}
...
}
and since class components extend React.Component, you can access the base class properties also using the this reference
However Functional components work on closures and the props are passed to the Functional component as arguments while executing it
const MyComponent = (props) => {
console.log(props)
}
Classes in Javacript work on prototypes. The render method is defined as a function in your class component which is called by React.Component in its lifecycle. However for a functional component the entire body can be considered as a render method
However with the arrival of hooks there is more focus providing lifecyle like utilities in functional components but the basic design remains the same
Hi there with regards to closures and scopes, hooks are function components therefor if you want to access a variable from an outer scope then closures would be done in a similar fashion as you would in javascript forexample.
function Example (){
const [exampletypes, setExampletypes`] = useState('');
// outer scope
// followed by Inner scope has access to variables of the outerscope.
function ExampleTwo(){
}
However some differences which make hooks cleaner and more developer freindly :
• In function components there is no this.props /this.state.
• Function components are more concise, cleaner and easier to read and write.
• Syntax is different, and how you manage state, scope and closures.
• For-example componentDidMount in classes is useEffect in functions.
• Better performance i suppose as there is lesser code.
Here are two component comparisons when exporting props with using functions and classes:
import React, {Component} from 'react'
export default class Greeting extends Component {
render() {
return (
<View style={{alignItems: 'center'}}>
<Text style={styles.textSize}>{this.props.name}</Text>
</View>
);
}
}
and function component with props:
import React,{useState} from 'react';
export default function Greeting(props) {
const [name] = useState(props.name)
return (
<View style={{alignItems: 'center'}}>
<Text style={styles.textSize}>{props.name}</Text>
</View>
);
}

Const = () => vs Class Functions function name() {} in React Native

I'm new to react native, I'm bit confused about components.
As I created first react native app I saw App.js the components in App.js created as per following code:
export default function App() {
...
}
and as I saw tutorials many people almost all people making components as per following code:
const FirstComponents = () => {
...
}
I'm also confuse about function components and class based components which created as per following code:
export default class FirstComponents extends Components(){
...
}
What is the difference between function and class base components?
Please provide me answer with examples. Your time will be appreciated.
In javascript there are multiple ways to create a function. For example:
function myFunction () {
//some action
}
const myFunction = () => {
//some action
}
These two are functions and makes the same thing.
Now second part of your question is "What is the difference between functional and class based components?"
Class based components used for controlling your state and for lifecycle methods(ComponentDidMount and etc...) in the past. And if you are not using state in your component or lifecyle methods, you would use functional based component. Basically if you have a small component with only some UI things, it was best to use functional components. However with React version 16.8 React team intruduced hooks.
Hooks provides the same concepts with your state and component lifecyle methods and more. With hooks you can control your component even if they are funcitonal components.
The first two snippets are similar in terms of declaration. Both are functional components. These are different from class based components. There are several differences:
Hooks can be used in only functional component, class based can't.
constructor is used to initialize this in the class component but in functional you don't require this.
Lifecycle hooks are not available in the functional component, they are part of class component.
You can use useEffect hook for a lifecycle hook like componentDidMount.
For a short example:
function App(){
const [count, setCount] = useState('');
}
In the above example "count" is a local state property of component and setCount is a method which updates the state.
class App extends React.Component{
constructor(props){
super(props);
this.state = { count: 0 };
this.increaseCount = this.increaseCount.bind(this);
}
increaseCount(){
this.setState({count: this.count+1});
}
// lifecycle methods like componentDidMount, componentDidUpdate etc.
render(){
return(
<button onClick={this.increaseCounter}>INCR</button>
);
}
}
In this class component you can see state is defined in the constructor and it is been updated with the setState method.
real time example will be too much to add, rather i suggest you to take simple examples to have a grasp of the concepts.

How does one React component call a method in another React component?

My page contains two completely separate React components (different files, different classes, no parent-child relationship).
How can one component call an instance method in another component? The problem seems to be obtaining the instance of the target component.
EDIT: Both components share the same parent (i.e. they are rendered in the same render() method) but I still don't know how to pass the reference of the target component to the calling component.
The short answer is: they don't.
It's not clear what you're trying to accomplish, so I can't speak to the specifics of your case, but the way React components "communicate" with one another is via state and props. For example, consider a Page component that has two child components, CompA and CompB, rendered something like this:
<Page>
<CompA />
<CompB />
</Page>
If CompA needs to pass something to CompB, this is done through state on the Page component, with that state exposed as props on CompA and CompB, something like this:
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
sharedValue: 42,
};
}
onChangeSharedValue(newValue) {
this.setState({ sharedValue: newValue });
}
render() {
return (
<div>
<CompA
sharedValue={this.state.sharedValue}
onChange={this.onChangeSharedValue}
/>
<CompB
sharedValue={this.state.sharedValue}
onChange={this.onChangeSharedValue}
/>
</div>
);
}
}
If CompA needs to change the shared value, it calls the onChange handler, which will change the state on the Page component. That value will then be propagated down to the CompB component.
There is no direct communication between components like you're describing; it is all done via state and props.
"Props down, Events up."
If you provide us a specific example of what you're looking for, I can update this post with a more specific response.
But in general, there are a couple of strategies that you can take. Some of them are presented here.
The preferred approach is to simply move your calling method to the parent component. It's a common strategy in React.
If you're not able to, then the next step would be to write an event handler for the parent, and then pass this event down to the first child component.
Use this event to pass information up to the parent, so that when it gets triggered, data can be passed as props down to the second component.
I only recently started doing React development and I found a solution for this problem that suits me. Admittedly, I haven't seen it referenced anywhere and when I showed it to a colleague who's been doing React for years, he kinda furrowed his brow and felt that it wasn't "right", but he couldn't really articulate to me why it's "wrong". I'm sure I'll be shouted down for it here, but I thought I'd share anyway:
File #1: objects.js
let objects= {};
export default objects;
File #2: firstComponent.js
import React from 'react';
import objects from 'objects';
class FirstComponent extends React.Component {
constructor(props) {
super(props);
objects['FirstComponent'] = this; // store a reference to this component in 'objects'
}
doSomethingInFirstComponent() {
console.log('did something in first component');
}
render() {
return (<div></div>);
}
}
export default FirstComponent;
File #3: secondComponent.js
import React from 'react';
import objects from 'objects';
class SecondComponent extends React.Component {
render() {
objects.FirstComponent.doSomethingInFirstComponent(); // call the method on the component referred to in 'objects'
return (<div></div>);
}
}
export default SecondComponent ;
When SecondComponent renders, it will trigger the console.log() in FirstComponent.doSomethingInFirstComponent(). This assumes, of course, that FirstComponent is actually mounted.
The "React Guys" that I know seem to think this approach is somehow evil. It uses a simple JavaScript object outside the normal React scope to maintain a reference to any existing objects that I choose to store there. Other than them telling me that "this isn't the way you do things in React", I haven't yet found a good explanation for how this will break or otherwise screw-up my app. I use it as a low-grade replacement for massive-overkill state-management tools like Redux. I also use it to avoid having to pass properties down through dozens of layers of React components just so something at the last level can trigger something waaaaay up in the first level.
That's not to say this approach doesn't have it's problems:
It creates an obvious dependency between the generic objects object, any component that is designed to store a reference to itself inside objects, and any component that wishes to utilizes those references. Then again, using any kind of global state-management solution creates a similar dependency.
It's probably a bad solution if you have any doubt that FirstComponent will be mounted before you try to call it from within SecondComponent.
I've found that just having the reference to a React component won't allow you to do all the things that React components can do natively. For example, it won't work to call objects.FirstComponent.setState(). You can call a method in FirstComponent, which in turn can invoke its own setState(), but you can't invoke FirstComponent's setState() directly from within SecondComponent. Quite frankly, I think this is a good thing.
You can, however, directly access the state values from the components referenced in objects.
This should only be done with "global" components (components that functionally serve as singletons). If, for example, you had a simple UI component called BasicSpan that did little more than render a basic span tag, and you proceeded to use that component over and over again throughout your React app, I'm sure it would quickly become an unmanageable nightmare to try to place references to these simple components in the objects object and then try to intelligently manage calls to those components' internal methods.
you can send an event as props and call it from other component.
Say you have a class
Class A{
handleChange(evt)
{
this.setState({
name:evt.target.value
})
}
render{
return(
<div>
<ComponentB name={this.state.name}{ onChange={this.handleChange}/>
</div>
);
}
}
Child Component
Class B{
handleChange()
{
//logic
}
render{
return(
<div>
<input type="text" onChange={this.props.onChange}/>
{this.props.name}
</div>
);
}
Here in Component B when you change the input it will call the method
of class A and update state of A.
Now getting the updated state as props in component B will give you
the changed text that you just entered

Unable to refer to immediately destructured props in class component, do I have to use `this.props` every time?

In a stateless functional component, we can use destructured props as the function arguments:
const Blah = ({ hello, world }) {
return <div>{hello} {world}</div>
}
This gives very clean code and not only is it obvious what props are being passed, we don't have to use this.props everywhere.
Having to use this.props all the time in a class component can take up a lot of room all over the component and is not nearly as nice to use:
class Blah extends Component {
render() {
return (
<div>{this.props.hello} {this.props.world}</div>
)
}
}
My questions is, what similar approach can we take for class components so that we don't have to use this.props everywhere?
One solution I can think of would be to destructure the props in the render method, but of course you would have to do that for every method in your class should you want to use the destructured name.
Nope I'm afraid there's no way to. The functional component is essentially a render() function of a class component, the "cleaniness" is kinda the same actually (:

Resources