Ad

React Does Not Re Render On Props Update

here is my render method of FormEl component.

return <div>
            <button type="button" onClick={this.clicked}>click to add 1 input</button>
            <Inputs count={this.state.childcount}/>
        </div>

in clicked method I update the childcount by 1 using setState

this is the Inputs class

class Inputs extends React.Component {
    constructor(props) {
        super(props);
        console.log("Input constructor is running.");
        this.state = {value: '', p: "p", count: props.count};
    }

    render() {
        let c = [];
        for (let i = 0; i < this.state.count; i++) {
            c.push(
                <div key={"id-" + (i * 10)}>
                    <input type="text" defaultValue={this.state.value}/>
                    <p> {this.state.p}</p>
                </div>);
        }
        return <div>
            {c}
        </div>;
    }
}

But, when I update the childcount in clicked, I can see FormEl is re-rendered, count in <Inputs.. is increased accordingly. But it does not call constructor of Inputs other than first (page loading) time.

Ad

Answer

Directly use this.props.count instead.

for (let i = 0; i < this.props.count; i++) {
Ad
source: stackoverflow.com
Ad