modify child component using its reference

Viewed 29

I'm trying to modify child component through the parent using its reference, but it doesn't seem to work, here's what I've tried already:

class App extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        
    }

    componentDidMount() {
        // I'm getting an error here that rightSide doesn't exist on App, and I got `Property 'classList' does not exist on type 'MutableRefObject '` when setting rightSide= useRef(null) 
        this.rightSide.classList.add("right");
    }

    render() { 
        <RightSide
            containerRef={ref => (this.rightSide = ref)}
        />
    }
}

const RightSide = (props: any) => {
    return (
        <div
            className="right-side"
            ref={props.containerRef}
            onClick={props.onClick}
        >
            <div className="inner-container">
                <div className="text">{props.current}</div>
            </div>
        </div>
    );
}
``
1 Answers

you can see your error from render function you are not returning anything that is why you see .classList.add() as is not a function.

This is how you render should be

render() { 
    return <RightSide
        containerRef={ref => (this.rightSide = ref)}
    />
}
Related