react parent component not getting updated

83 Views Asked by At

I have a parent component (functional), child component (class). The parent component is print component which uses react-to-print to show print-preview the child component. I have a scenario where I have to update the style (height) of a <textarea>. In UI I can get it work using ref to set the height, but when the print component triggers it's not taking the new style. It always takes the old style.

Parent component

const PrintCompoent = (props) => {
    // print component logic
    return (
        <ChildComponent
            // required props
        />
    );
}
export default PrintCompoent;

Child Component

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
        this.noteTextRef = React.createRef();
        // state variables
    }

    UNSAFE_componentWillReceiveProps(props) {
      this.noteTextRef.current.style.height = "inherit";
      this.noteTextRef.current.style.height = `${this.noteTextRef.current.scrollHeight}px`;
    }

    // component logic

    render() {
        return (
            // html
            <textarea
              cols="50"
              ref={this.noteTextRef}
              className="form-control visit-notes"
              id="desc"
              name="note"
              onChange={this.handleUpdate}
              value={'some value'}
             />
        );
    }
}
export default ChildComponent;

I already tried with componentDidUpdate. Didn't work.

Edit: sample scenario

1

There are 1 best solutions below

3
On BEST ANSWER

So I take a look at your example and found few strange things.

To make your component work as expected, first of all, remove childComponent from App.js.

Then remove display: none from your print component. And after that everything works as expected.

You actually have few childComponents, one hidden and one that you actually see, and you provide ref to one that hidden.

** UPDATED **

You need to create ref in parent component and pass it down to your print component and do not render a one more child component in print component