0

I have react component which returns an integer. Structure of the class component is as follows:

class MyClass extends Component {
   constructor(props) {
        super(props);
        this.state = {
            variable : 0
        }
    }
    componentDidMount(){
       // do some works
       this.setSate({variable:$someValue});
    }
    render(){
        var temp = this.state.variable;
        return temp;
    }
}

I need to fetch the value returned from MyClass in another class component in React within render. If I call like,

render () {
  return (
    <div>{Myclass}</div>
  );
}

it works fine. is there any way to call this outside return, and assign the value to a variable?

2 Answers 2

1

Try utilizing 'this.props' instead. You can pass in something like this

   class MyClass extends Component {
   constructor(props) {
        super(props);
        this.state = {
            variable : 0
        }
    }
    componentDidMount(){
       // do some works
       this.setSate({variable:$someValue});
    }
    render(){
        const {variable} = this.state
        return (
             <MyOtherClass variable = {variable}/>
         );
    }
}

And in MyOtherClass:

render() {
    const {variable} = this.props
    return (
        <div>{variable}</div>
    );
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to extend MyClass and call super.render()

class MyOtherClass extends MyClass {

    render() {
        const value = super.render();
        return (
            <div>{value}</div>
        );
    }
}

edit: working example in codesandbox.io

2 Comments

need to access the integer for further processing @Teneff
It says as Super expression must either be null or a function, not undefined @Teneff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.