Dan
Dan

Reputation: 159

How to pass variables from class to class

Alright, so I'm trying to simplify a project I'm working on, but of all the information I've read on the internet, none of it has answered my question. My doubt is how can I pass variables (the name of the variable, and its value) from one class to another class? Should I use props? Should I just do something similar to this.state.variable? How can it be done? I'll write a sample code just to show what I'm trying to do more visually, however, this is not my actual code. Thanks for helping :)

class FishInSea{
    constructor(props){
        super(props);
        this.setState({fishInSea: 100});
    }
    render(){
        return(
            <div>Fish in the sea: {this.state.fishInSea}</div>
        );
    }
}

class FishInOcean{
    constructor(props){
        super(props);
        this.setState({fishInOcean: <FishInSea this.props.fishInSea/> * 1000});
    }
    render(){
        return(
            <div>Fish in the ocean: {this.state.fishInOcean}</div>
        );
    }
}

export default FishInOcean;

Upvotes: 2

Views: 5739

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 33974

You need to first make both the classes in to React components. Since both the classes modify the state so they called as statefull components. The class has to extend the Base class of React i.e., Component.

in constructor we only do state initialisations but won’t modify the state there. But you are modifying the state which isn’t correct. Instead move setState to componentDidMount.

Say suppose in FishInSea class you have fishInSea and you want to pass it to FishInOcean component as props.

Check below two corrected components how they are passed from one component to the other

  import React, { Component } from “react”;
  class FishInSea extends Component{
       constructor(props){
            super(props);
            this.state = {
                 fishInSea: 100
            }
       }
       componentDidMount(){
             this.setState({fishInSea: 100});
       }
       render(){
           const { fishInSea } = this.state;
                return(
                   <div>Fish in the sea: 
                         <FishInOcean fishInSea={fishInSea} />
                   </div>
            );
        }
   }


    import React, { Component } from “react”;
    class FishInOcean extends Component{
         constructor(props){
             super(props);
             this.state = {fishInOcean: 1000}
         }
         componentDidMount(){
             this.setState({fishInOcean: 1000});
          }
        render(){
           const { fishInOcean} = this.state;
           const { fishInSea } = this.props;
           return(
               <div>Fish in the ocean: {fishInOcean}
                    {fishInSea}
               </div>
           );
       }
   }

  export default FishInOcean;
  /*There was a typo*/

Upvotes: 2

Related Questions