zloctb
zloctb

Reputation: 11194

import module error this is undefined

CounterView.js

import React from 'react';
const  CounterView =   <div>
    <h1>{this.state.counter}</h1>
    <button onClick={this.handleDecrement}>-</button>
    <button onClick={this.handleIncrement}>+</button>
</div>;
export default CounterView;

Counter.js

import React from 'react';
import CounterView from '../ComponentsView/CounterView.js';

class Counter extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            counter: 0,
        }
    }

    render() {
        return (
           < CounterView />
        )
    }

}

Bu I got error:

Uncaught TypeError: Cannot read property 'state' of undefined

Please help me. And sorry bu I have second popular for me question : Why I must require

  import React from 'react';

in each file in my application ? He require only one in first call?

Upvotes: 1

Views: 204

Answers (1)

bennygenel
bennygenel

Reputation: 24680

Change your code accordingly. You can't reach another components state from a child component. You can use props instead of state.

CounterView.js

import React from 'react';
class CounterView extends React.Component{ 
    render() {
        return (
            <div>
                <h1>{this.props.counter}</h1>
                <button onClick={this.props.handleDecrement}>-</button>
                <button onClick={this.props.handleIncrement}>+</button>
            </div>
        );
    }
}
export default CounterView;

Counter.js

import React from 'react';
import CounterView from '../ComponentsView/CounterView.js';

class Counter extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            counter: 0,
        }
    }
    handleDecrement() {
      // do the decrements here
    }
    handleIncrement() {
      // do the increments here
    }
    render() {
        return (
           <CounterView counter={this.state.counter} handleDecrement={this.handleDecrement.bind(this)} handleIncrement={this.handleIncrement.bind(this)}  />
        )
    } 
}

Upvotes: 1

Related Questions