Nikola Lukic
Nikola Lukic

Reputation: 4226

Component communication - React JS

How to make state change from outside of class or from prop.SomeFunction () ? I use typescript in combination. Yes i already have the class :

CLASS :

import * as React from "react";
import { Label } from "../../components/label/label";
import { TextBox } from "../../components/textBox/textBox";
import IApp from "../../interfaces/global-interfaces";
import { myStyle } from "./style";

interface HeaderI {
    background: string;
    myFunc(): void;
    // elements: any[];
    // add(id: number, content: any, event: any): void;
}

interface HeaderStateI extends IApp.ElementI {
    background: string;
    elements: any[];
}

export class Header extends React.Component< HeaderI, HeaderStateI , any > {

    public myRef: React.RefObject<Label>;

    constructor(args: any) {
        super(args);
        this.state = { enabledComponent : true,
                       visibility: true,
                       debugView: false,
                       background: args.background,
                       elements: [],
                    };

        this.myRef = React.createRef();
        this.add = this.add.bind(this);

        console.log("state elements:" , this.state.elements);
    }

    public test() {
       alert("Y click on header element");
    }

    public printMe() {
      console.log("Layout Header is active :");
    }

    //  setText = (e: React.ChangeEvent) => {

      // this.setState ( { enabledComponent : true , background :  (e.target as HTMLInputElement).value } );

    // }

    public render() {

        if ( this.state.debugView === false ) {

            return (
                <div style={myStyle} onClick={this.addN} >
                <Label name="headerName" text="i am header paragraph!" />
                {this.state.elements.map((i: any) => {
                  return <span key={i} >{i}</span>;
                })}
                </div>
              );

        } else {

            this.printMe();

            return (
                <div style={myStyle} >
                <Label ref={this.myRef} name="headerName" text="i am header paragraph!"/>
                {this.state.elements.map((i: any) => {
                   return <li key={i} >{i}</li>;
                })}
                </div>
              );

        }

    }

    public componentDidUpdate(prevProps: any) {

        // Typical usage (don't forget to compare props):
        console.warn("prevProps name is: " + prevProps.name);
        if (this.props.background !== prevProps.background) {
          this.printMe();
        } else {
            console.log("Background is same no update.");
        }

    }

    public add = (id: number, content: any, event: any ) => {

        this.setState(
          {
            elements: [React.createElement("div", { key: 2 , onclick : null }, "tyest 12")],
            visibility : false,
          },
        );

        // tslint:disable-next-line:no-unused-expression
        console.log(" add from class in state elements,  visible is " , this.state.visibility );

    }

    public addN(event: MouseEvent | Event) {

        this.setState(
            {
              elements: [React.createElement("div", { key: 2 , onclick : null }, "tyest 12")],
              visibility : false,
            },
          );
        // tslint:disable-next-line:no-unused-expression
        console.log(" add from class in state elements,  visible is NNNN " , this.state.visibility );
    }

}

MAIN FILE :

const AddNewElement = Services.addNewElement;
const collectMe = <Header background="#127654"/>;

ReactDOM.render(
    <>
    {collectMe}
    <h3>Page title - inline text only example </h3>
     <Title name="title" text="Hello react title" />
     <Label name="root" text="I am text label component!"/> <br/>
     <TextBox name="root" text="I am textBox component!"/>
    </>,
    document.getElementById("root"),
);

// This space is already out of class so why i can't change it ???

collectMe.props.background = "#121212";
console.log(collectMe.props);

But examples are too pure with out args passing etc... Is it react just a commercial puffed-up project.

Upvotes: 0

Views: 72

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

props are read-only.

Whether you declare a component as a function or a class, it must never modify its own props.

What you need to do here is to use state. And to use state, you need to have class based component. Then, you can update the parent component state from child component using a callback function.

Take a look at this post to update the parent state from child component.

Upvotes: 2

Related Questions