Reactjs- Unable to access class variable inside function in tsx - reactjs

I am unable to access class variable inside a function, following is my code:
export class MyClass extends React.Component<{}, {}>{
public myArray: string[]; //I want to access this variable
constructor() {
this.state = { name: "" }
}
private _hello = () => {
console.log(this.state.name);
console.log(this.myArray) //this lines throws undefined
}
render(){
<button onClick={this._hello}>Click</button>
}
}

Bring the function variable outside constructor. Btw render method should be outside constructor.

Try not to use private and public on react, here is some explanation, you could use:
const myArray: string[]; //I want to access this variable
export class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
}
}
hello = () => {
console.log(this.state.name);
console.log(myArray) //this lines throws undefined
}
render(){
return (
<button onClick={this.hello}>Click</button>
)
}
}

Related

How to call another class method from main class without changing the state of main class in react with typescript

I'm using react with typescript in SharePoint framework. I want to call method in another class from main class.
I need same 1 as output in console for all three console.log calls
class MainPage extends React.component<Iprops, Istate>
{
constructor(props?: Iprops, state?: Istate) {
super(props);
this.state = {
status: 0,
};
}
public firstMethod(e): void {
this.setState({ status: 1 });
console.log(this.state.status);
var Obj = new AnotherClass();
Obj.secondMethod();
}
public ThirdMethod(): void {
console.log(this.state.status);
}
public render(): React.ReactElement<Iprops> {
return <div> <button onClick={this.firstMethod.bind(this)}>Click me</button>
</div>;
}
}
class AnotherClass extends React.Component {
constructor() {
super(props);
}
public SecondMethod(): void {
var obj1 = new MainPage();
console.log(obj1.state.status);
obj1.thirdMethod();
}
}
Thanks in advance

Reactjs: Parent function call triggered by a child

So I am building my first react project and stumbled upon following problem:
In my App.js (main application) I got a function and render my components:
class App extends Component {
constructor(props) {
super(props);
this.candidateCounter = 0;
this.setCandidateVote = this.setCandidateVote.bind(this);
}
...
setCounter (name) {
this.candidateCounter++;
console.log(this.candidateCounter);
}
render() {
...
<Candidates setCounter={this.setCounter} />
}
}
The child component Candidates.jsx has another function and thus calls another component:
export class Candidates extends React.Component {
constructor(props) {
super(props);
this.AppProps = props;
}
...
registerVote(name) {
...
this.AppProps.setCounter(name);
}
render() {
...
<MyButton id={this.state.candidates[i].name} register={this.registerVote} />
}
And the last component MyButton.jsx looks like this:
export class MyButton extends React.Component {
constructor(props) {
super();
this.ParentProps = props;
this.state = { active: false }
}
buttonActiveHandler = () => {
this.setState({
active: !this.state.active
});
if (this.state.active === false) {
this.ParentProps.register(this.ParentProps.id);
}
else {
...
}
}
render() {
return (
<Button content='Click here' toggle active={this.state.active} onClick={this.buttonActiveHandler} />
);
}
}
I have successfully debugged that all functions calls are working except when the grandchild MyButton has triggered the registerVote() function in my Candidates module. Logging in this method gets printed but it cannot call this.AppProps.setCounter() from the parent App. I receive the following error:
TypeError: Cannot read property 'setCounter' of undefined
I hope this wasn't too complicated explained, any help is appreciated :)
Simply bind the function in the constructor of the class as #qasimalbaqali stated in his comment.
constructor(props) {
super();
this.registerVote = this.registerVote.bind(this);
}

how do I declare additional property for React class component?

I rewrite my React Project with TypeScript. now I know how to declare property interface and state interface for a Class Component, simple like this:
export interface ComponentProps {
propName: string
}
interface ComponentState {
stateName: number
}
class myComponent extends React.Component<ComponentProps, ComponentState> {
...
}
but error accur when I do something in componentDidMount() lifecycle:
componentDidMount() {
this.customProperty = 26; // here I could save an id returned by setInterval to cancel it in the componentWillUnmount() for example.
}
[ts] Property 'customProperty' does not exist on type 'MyComponent'. [2339]
What can I do to declare additional property correctly, not just simple silence the error.
I've learned the basic of typescript.
import React, { Component } from 'react';
export interface CheckoutProps {
total: number;
customer: string;
}
interface State {
isChecking: boolean;
}
class Checkout extends Component<CheckoutProps, State> {
state = {
isChecking: false
};
componentDidMount() {
this.customProperty = 'sean';
}
render() {
return <div>hello</div>;
}
}
export default Checkout;
Class level properties can be defined after the class declartion,
They can be initialized either at the time of declartion or in constructor.
Change your Class To :-
class Checkout extends Component<CheckoutProps, State> {
customProperty:string=''; //Here,you can define your class level properties
state = {
isChecking: false
};
componentDidMount() {
this.customProperty = 'sean';
}
render() {
return <div>hello</div>;
}
}
Hope this helps,
Cheers !!
You can declare it within the class:
class myComponent extends React.Component<ComponentProps, ComponentState> {
private customProperty: string = '';
componentDidMount() {
this.customProperty = 'sean';
}
}

Call function inside constructor of component in react?

I have to call function inside constructor as working from call backs which i have to include in constructor but this is "undefined" in constructor.
class XXXXX extends React.Component {
constructor(props) {
super(props);
this.state =
{
chargebeeInstance : windowChargebeeinit({
site: "xxxxxxxxxxxxx-test"})
}
this.statechargebeeInstancesetCheckoutCallbacks(function(){
return{
close:function(){
this.moveToNextStep();
}
}
})
}
moveToNextStep(){
this.props.jumpToNextStep(3);
}
I am not able to call moveToNextStep as this is undefined
this is scope issue, you have to preserve scope before this.statechargebeeInstancesetCheckoutCallbacks function mentioned below
class XXXXX extends React.Component {
constructor(props) {
super(props);
const me = this
this.state =
{
chargebeeInstance : windowChargebeeinit({
site: "xxxxxxxxxxxxx-test"})
}
this.statechargebeeInstancesetCheckoutCallbacks(function(){
return{
close:function(){
me.moveToNextStep();//scope issue, this will not be available here
}
}
})
}
moveToNextStep(){
this.props.jumpToNextStep(3);
}
Hope this will help
You need to bind the function up to the current closure. Try this:
class XXXXX extends React.Component {
constructor(props) {
super(props);
// I believe this is what you are missing.
this.moveToNextStep = this.moveToNextStep.bind(this)
this.state = {
chargebeeInstance : windowChargebeeinit({
site: "xxxxxxxxxxxxx-test"
})
}
this.statechargebeeInstancesetCheckoutCallbacks(function(){
return{
close:function(){
this.moveToNextStep();
}
}
})
}
moveToNextStep(){
this.props.jumpToNextStep(3);
}
}

Cannot read property 'checked' of undefined, from React.Component static funtion

I have a React.Component and i want to call this static function from the many different React.Component.
class Categories extends React.Component {
constructor(props) {
super(props);
this.getCheckedCategories = this.getCheckedCategories.bind(this);
this.state = {
checked: [],
unchecked: []
};
}
static getCheckedCategories() {
return this.state.checked;
}
}
So I tried to connect the function.
import Categories from './product/checkboxes';
class FullWidthGrid extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
const { classes } = this.props;
const checkedCategories = Categories.getCheckedCategories();
}
}
static functions can't access this, i.e. static method calls are made directly on the class and are not callable on instances of the class. You can read more on that here.
So in your case you could do:
class Categories extends Component {
state = {
checked: [],
unchecked: []
};
static getCheckedCategories = (klass) => {
return klass.state.checked
}
render() {
return (
<div>{Categories.getCheckedCategories(this)}</div>
);
}
}
Working example here.
That's the purpose of static function. It cannot access the instance (this).
You can have multiple instances of class but only one static function/property.
As a workaround (depend on what you want to do), you can use static property to store your state:
class Categories extends React.Component {
constructor(props) {
super(props);
Categories.state = {
checked: [],
unchecked: []
};
}
static getCheckedCategories() {
return Categories.state.checked;
}
}
However it won't work with setState since it is an instance method.
Imagine situation when you have muptiple Categories components and each one has different checked/unchecked categories. What would then Categories.getCheckedCategories() function returns?
If you want to have shared state (checked categories), I would recommend you to pull out the state out of the component. For example store it in parent component and pass it as props to child components. Or use state library like redux. You could also use react's context to manage shared state.

Resources