Search code examples
javascriptreactjsreact-propscomponentwillreceiveprops

React props value is undefined


This is my parent code:

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: [],
        };
    }
    componentDidMount() {
        this.getTags();
    }

    getTags() {
        //method gets tags from the backend
    }
    render() {
        return <Child tags={this.state.tags} />;
    }
}

And this is basically my child component:

export default class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: props.tags,
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            tags: nextProps.tags,
        });
    }
}

But when I console log tags somewhere in the Child component, it is undefined. Maybe it is undefined because the child component gets rendered before the parent component calls the method getTags? Or is there any other problem with this code? And how can I avoid this problem that tags are undefined in the child component?

Cheers


Solution

  • To avoid your problem, you shouldn't be rendering your Child component until the this.state.tags has any useful values.

    Here is how you can do it and also show a "Loading..." text, so the user isn't worried the page is broken.

    class Parent extends Component {
        constructor(props) {
            super(props);
            this.state = {
                tags: [],
            };
        }
        componentDidMount() {
            this.getTags();
        }
    
        getTags() {
            //method gets tags from the backend
        }
        render() {
            return this.state.tags.length ? (
                'Loading...'
            ) : (
                <Child tags={this.state.tags} />
            );
        }
    }