0

This may be an anti pattern, but I'm using fixed-data-table to display tables with changing columns. The resize function resizes the width of each column based on a state change. However, I need to build the state or columns from props received. I can't update the state from the render function. Is there a better way to go about this? My best solution so far was to generate the state width to 100, but this is temporary.

constructor(props) {
    super(props);var columnWidths ={
            recordid: 40,

        };
    for(var i=0; i<100;i++) {
        columnWidths[i]=200
    }

    this.state = {
        columnWidths
    }; 
    this._onColumnResizeEndCallback = this._onColumnResizeEndCallback.bind(this);
}
_onColumnResizeEndCallback(newColumnWidth, columnKey) {
    this.setState(({ columnWidths }) => ({
        columnWidths: {
            ...columnWidths,
            [columnKey]: newColumnWidth,
        }
    }));
    console.log(newColumnWidth + " " + columnKey)
}
lastlink
  • 1,505
  • 2
  • 19
  • 29

2 Answers2

0

So apparently I can use componentWillUpdate() to update my react state from props. ThecomponentWillReceiveProps() would not update my props pulled from an api call. However, I need the state to be updated before the props are pulled into the render. This Almost Solution works if they are prefilled out, but won't when the page refreshes:

componentWillUpdate() {
    var columnWidths = {
        recordid: 40,
    };
    Object.keys(this.props.fields).map(key => {
        columnWidths[this.props.fields[key].Order] = 200;

    })
    this.state = {
        columnWidths
    };

}

I had to add the || or symbol to allow it on first render and then these are autocreated after the props are loaded

width={columnWidths[field.Order]||200}
lastlink
  • 1,505
  • 2
  • 19
  • 29
0

I'm not sure I understand your question, but you can initialize your state in the constructor(props) function, then use setState based on this.props in componentWillMount or componentDidMount, and also in componentWillReceiveProps(newProps).

So it seems you need to call setState in lifecylce method componentWillMount or componnentDidMount.

Fay
  • 173
  • 13
  • The componentWillMount and componnentDidMount had issues because I was waiting from an api call to get the names of the columns and they didn't always finish the REST calls in the same order. The update worked the best. – lastlink Aug 12 '17 at 12:24