skip to Main Content

So basically, I have a delete button in my parent component and whenever I click on that button, some function should be called that will change or reset a state variable of child component. I am unable to think of a solution here. I basically am a Java developer but now have to handle some frontend stuff as well that involves React. Any help would be appreciated!

Unable to think of an approach here.

3

Answers


  1. You should learn more about the basics of React.

    Anyway here is an example:

    const ChildComponent = (props) => {
    
    const {onButtonClick} = props
    
      return (
        <button onClick={onButtonClick}>Set to false</button>
      
      )
    
    
    }
    
    const Parent = () => {
      const [booleanButton,setBooleanButton] = useState(false)
    
    
      const onButtonClick = () => setBooleanButton(!booleanButton)
    
      return (
        <>
          <ChildComponent onButtonClick={onButtonClick}/>
        </>
      )
    
    }

    If your state management is going to be more complex and you’ll need to access the values from a diffrent component, or even a diffrent component tree you should use React context or Redux.

    Here’s a Codesandbox example

    Login or Signup to reply.
  2. You can lift the state from the child to the parent component and pass the required parent state as a prop to the child component.

    You can read more about this here :
    https://legacy.reactjs.org/docs/lifting-state-up.html

    Login or Signup to reply.
  3. Like another answer mentioned, you need to "lift" the state up in the parent component, and have that update it. The state can be passed to the child component as a prop.

    Here is an example using class components:

    import { Component } from 'react';
    
    export class Parent extends Component {
      constructor(props) {
        super(props);
        // Store the state in the parent component
        this.state = {
          foo: [1, 2, 3],
        };
      }
    
      handleDelete() {
        this.setState({ foo: [] });
      }
    
      render() {
        return (
          <div>
            // Pass it to the child component as a prop
            <Child foo={this.state.foo} />
            <button onClick={this.handleDelete.bind(this)}>Delete</button>
          </div>
        );
      }
    }
    
    export class Child extends Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return <div>{this.props.foo}</div>;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search