0

So I've been trying to access a parents state from a child component, however I keep getting either an error message or it doesn't work all together. I have found multiple solutions online, however none of them work for React with Typescript.

So here is an simplified code example of what I'm trying to do.

export default class parent extends React.Component {

state= {
exist: true
}

render() {
    return (

    <div>
        <child>
    <div>
    )
}


export default class child extends React.Component {


componentDidMount = () => {
    document.getElementById("theText").value = "It does exist!"
}

render() {
    return (

    <div>
         <h1 id="theText">It Doesn't exist</h1>
    <div>
    )
}

PS// This is NOT the code I'm working on! I just quickly wrote it so it's easier to see what I'm trying to do!

1 Answers1

0

You can pass the state from your parent to the child using something that's called props. These props can be variables, but also functions. Of course, since it's typescript you need to define this. The type of the props can be defined with an interface:

interface ChildProps {
    Exists: boolean;

    // You can skip this one if you don't want to alter the state
    // in the parent from the child component.
    SetExists: (value: boolean) => void;
}

The interface is used as a generic argument in React.Component<ChildProps>

export default class child extends React.Component<ChildProps> {
    componentDidMount = () => {
        document.getElementById("theText").value = "It does exist!"
    }

    render() {
        // Depending on the state of the parent, something can be rendered here.
        if(this.props.Exists)
            return <h1>Does exists! :)</h1>;
        else
            return <h1>Doesn't exist :(</h1>;
    }
}

You also need to change the parent component a little bit. That will look like this:

export default class parent extends React.Component {
    state = {
        exist: true
    }

    render() {
        return (
            <div>
                <child

                    // Here, the state is passed to a child component as if it
                    // were an argument of a function.
                    Exists={this.state.Exists}
                    SetExists={(x) => this.setState({ Exists: x })}
                >
            <div>
        )
}

I hope this is helpful and will solve your problem. If not, let me know so we can continue to search for a solution. :)

NielsB95
  • 32
  • 3