Converting functional component to class based component - javascript

I need to convert a functional component to a class based component. I am fairly new to React but I have tried to convert the component. I get the error - ReferenceError: Cant find variable: Props
My question is, where do I add props which was present in the class based component to make the conversion work ?
The class based component which is a modal with a form triggered from a parent component,this works well. The form uses state variables which dont work in a class based component so I need to convert the current functional component to a class based component. I'm using version 16.6.3 of React because other packages do not work with newer versions of React-Native so I cant use hooks with this version.
Functional component
const ShowModal = props => (
<Modal
visible={props.display}
animationType="slide"
onRequestClose={() => console.log("closed")}
>
...Other stuff in here.
</Modal>
);
export default ShowModal;
Class based component
export default class ShowModal extends Component {
state = {
};
render() {
return (
...Other stuff in here
);
}
}
I get the error - ReferenceError: Cant find variable: Props

In class based components props is exposed in the main scope of the class. You should read it using this keyword
class Component extends React.Component{
render(){return this.props.value}
}

I presume you want to use State, as the reason for moving to a Class component. Instead I suggest to use React Hooks which is the newest and elegant approach.
const ShowModal = props => (
const [state, setState] = React.useState({});
<Modal
visible={props.display}
animationType="slide"
onRequestClose={() => console.log("closed")}
>
...Other stuff in here.
</Modal>
);
React Hooks: https://medium.com/frontmen/react-hooks-why-and-how-e4d2a5f0347

Related

React adding FloatingMenuButton Package Parsing error: Unexpected token

I am new to React and trying to add the Floating Menu Button from this Package.
Adding this I get following Error.
Parsing error: Unexpected token
I have uploaded the Code.
https://codesandbox.io/s/adding-floatingmenu-2tfxe?file=/src/App.js
I also have another Question. What is the difference of adding render() {} infront of return() or just leaving return()?
Update
I have Updated my Code inside codesandbox, there i do not receive an Error, after I copied it into VSCode i receive following error.
You can use react hooks only in functional components. If you use class components you not allowed to use hooks.
But what is a Hook?
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
Second question the same situation, render() uses in class components, in functional components you just use return(<></>)
Please read hooks owerview:
https://reactjs.org/docs/hooks-overview.html
If you want to initialize the isOpen state as false, here's a minimal example of that
import React, { Component } from "react";
import {
FloatingMenu,
MainButton,
ChildButton,
} from "react-floating-button-menu";
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
isOpen: false
}
}
render() {
return (
<FloatingMenu
slideSpeed={500}
direction="up"
spacing={8}
isOpen={this.state.isOpen}
>
<MainButton
backgroundColor="black"
onClick={() => this.setState({ open: !this.state.isOpen })}
size={56}
/>
</FloatingMenu>
);
}
};
Make sure you import Component from 'react' at the top. Render method is required when you're making a React component using a class method which you are using. It's a type of lifecycle method which is invoked when the component needs to update. The return statement only returns the data/JSX elements wherever it is being used.
If you are using functional components, you don't need a render method since they return the react elements themselves

Create custom hooks state in react and Manipulate global state from everywhere without using any third party state management library

You can get, reference here in this StackBlitz Link
I have one folder file todoState.ts in models folder of project. This todoState.ts used for managing global state of application using custom hooks. I need to perform following tasks on global todoState.ts..
Add new State
Remove state
update state
here is code of todoState.ts.
import { useState, useEffect } from "react";
const todoState = (todo?, callback?) => {
const [todos, setTodos] = useState([todo]);
useEffect(()=>{
setTodos(todo);
},[])
return [{todos, setTodos}];
}
Now, I have Two user defined components which are dependent on globalState. which are 1. <TodoForm /> and <TodoListLineItem />
Both of above component is rendered inside index.tsx.
How can I manage global state from all the components including index.tsx , <TodoForm /> , <TodoListLineItem />. Here...
<TodoForm /> , is used to add to tasks to list.
<TodoListLineItem />, is used to display all added tasks from TodoForm component. when user hover over to each todo list item then user can able to remove perticular tasks-item from global management state.
Which one is best and reusable way to implement this global management state feature?
How one component changed state from A to B is reflected on related component by just manipulating global state object of application. If I put useState([]) into index.tsx then it will works well, But I want to manage state from TodoState.ts file. Thank You.
export default todoState;
Finally , I found and learned New concepts for React-Context API. You can checkout here StackBlitz Link
To manage global states React provides context-api. Use only when you have multiple level of component properties pass down in component tree from Top to bottom. I used very small example to understand context api for my different use-case.
First of all we need to use two context..
createContext [ used to create global state context ]
useContext [ used to get states from context from child component ].
To work with Context I created one <context.Provider> component. and all state management tasks are done with only this component level only. all child component just send events of what to do. and global context of provider component changes accordingly.
firstly, Create context..
export interface ItodoContext{
todoState? : Itodo[];
addNewTodoState?: (state?: string) => void;
removeTodoItemByIndex? : (index?: number) => void;
}
export const todoContext = createContext<ItodoContext[]>([{}]);
As, I am using React-Typescript functional component, as per Interface of context i defined all tasks of states. I passed all TodoState, function to manipulate TodoState like addNewTodoState, removeTodoItemByIndex.
then create Provider of context..
const allTodoStates = {
todoState,
addNewTodoState,
removeTodoItemByIndex
}
return(
<todoContext.Provider value = { [allTodoStates]}>
{props.children}
</todoContext.Provider>
)
Then I set Provider as parent component in tree in index.tsx component like this..
const App: FC = () => {
return (
<div className="h-100 w-100">
<TodoStateProvider>
<Navbar />
<div className="container">
<TodoForm />
<TodoListLineItem />
</div>
</TodoStateProvider>
</div>
);
}
See above all components now child of <TodoStateProvider> parent component.
When I need to add new state to context is inside <TodoForm> and how we can add state is as below code...
const [{addNewTodoState}] = useContext(todoContext);
const sendTodoItem = (e) => {
addNewTodoState(todoInput.trim());
}
and so on.. provider component has value property, and we can get those properties from child using useContext() hook. as we used above. See full working demo I have attached in above StackBlitz Link.

Pass React Props to a Separate JS File

I'm trying to pass props for width from a parent component to a child JS file, but cannot seem to get the props value in the child JS file. The parent is the following:
import React from 'react';
import Child from './Child';
export default class Home extends React.Component {
state = {
width: 1000
}
render(){
return(
<div>
<Child width={this.width} />
</div>
);
}
}
The separate child JS file is the following:
import React from 'react';
const svgWidth = 650, // Load prop here
svgHeight = 340;
What I've tried is the following but is not working for me:
import React from 'react';
const Child = (props) => {
console.log({props.width}); // Getting an error that ',' is expected
return {props.width};
}
Can someone please help me with passing the width value from ?
Change to the following, as you should access state through this.state, like so:
<Child width={this.state.width} />
Either use the prop drilling, hence pass the values from parent to child as a prop.
But exact answer to your question will be :
create a blank object in separate js file and export it and then in componentDidMount populate that object with the props which you want to save. Next time when ever you will use that object anywhere in normal js file you will get the props.
If you intend to pass props to a child component, then I would start with the following:
import React from 'react';
import Child from './Child';
export default class Home extends React.Component {
constructor(props) { // don't forget to add a constructor
super(props); // also required
this.state = {
width: 1000
}
}
render(){
// to pass state use {this.state}
return(
<div>
<Child width={this.state.width} />
</div>
);
}
}
However, if that is not the case and instead you want to export state to a separate js file (that may not even be a React component), then you may have to look at export syntax. I am struggling with a similar problem right now and I already tried what Vikash Kumar suggested without success. This is explained on this question but I was not successful with that approach either: export function inside react component or access state in same file outside of component

Stateful and Functional stateless components

How to convert Stateless functional components to stateful component in order to use lifecycle methods and passing props to it like Stateless Component.
( export default JobCard = (props) => {
............
}
)
I need to convert this to stateful component in order to use life-cycle method and pass props to the return function like how props is passed here. Thank you in advance.
You can do it like this:
export default class JobCard extends React.Component {
render() {
// here you can access props passing down from
// parent components like: this.props
return (
<div>
Hi, I'm a super smart component!
</div>
);
}
}

How can I pass props down in Angular 2+ like React?

In react I can arbitrarily pass props down like so:
function SomeComponent(props) {
const {takeOutProp, ...restOfProps} = props;
return <div {...restOfProps}/>;
}
How can I do the same thing in Angular?
--
More specifically, I want to write a custom dropdown component and pass props down to a select box.
As opposed to React components, Angular components aren't recompiled on input changes and use #Input property decorators to enable change detection. All properties that are expected to be passed should be explicitly defined as component inputs.
There are no better options than this one for custom select component. It's possible to read static attributes from current component element and set them on nested component element, but this won't set up bindings.
As for React recipe for deep props in wrapped components:
const Baz = props => <p>{props.baz}</p>;
const Bar = props => <Baz {...props} />;
const Foo = props => <Bar {...props} />;
This is usually handled by Angular DI and a hierarchy of injectors. A provider can be defined on respective injector in order to make data and behaviour available to nested components.
Actually it is not the answer on your question but perhaps it helps you.
You can add one custom directive with all params you need.
import { Directive, ElementRef } from '#angular/core';
#Directive({
selector: '[defaultConfig]'
})
export class DefaultDropdownConfigDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
// your default config
}
}
<my-dropdown defaultConfig></my-dropdown>
For more details you can read this

Categories