Home > Software design >  How to use seState from child component?
How to use seState from child component?

Time:01-09

In the case, how to use setDisabled from child component ?

const ChildButton = () => {
  const [disabled, setDisabled] = useState(false);

  return <div onClick={disabled ? null : console.log('do something')} />
}

import ChildButton from './ChildButton';

const Parent = () => {

  const controllSetStateFun = () => {
    // use the child coomponent setDisabled then I can re-render child component from Parent
  };

  return (
    <div>
     <ChildButton />
    </div>
  );
}

CodePudding user response:

You can look into useImperativeHandle:

function Component(props, ref) {
  const [disabled, setDisabled] = useState(false);

  React.useImperativeHandle(ref, () => ({
    method: () => {
      setDisabled(true);
    },
  }));
  return <div onClick={disabled ? null : console.log('do something')} />;
}
Component = React.forwardRef(Component);

In this example, a parent component that renders <Component ref={myRef} /> would be able to call myRef.current.method().

CodePudding user response:

You need to lift the state up

  1. Take your state in the parent component.

  2. Pass the set state function as a prop to the child component.

  3. Call the setState function from the child component.

    const Parent = () => { const [disabled, setDisabled] = useState(false);

    const controllSetStateFun = () => { // use the child coomponent setDisabled then I can re-render child component from Parent };

    return ( ); }

    const ChildButton = ({disabled,setDisabled}) => { //you can access setDisable from here ... return <div onClick={disabled ? null : console.log('do something')} /> }

CodePudding user response:

you can do this by passing the props also

const ChildButton = ({disabled, setDisabled}) => {
 

  return <div onClick={disabled ? null : console.log('do something')} />
}

const Parent = () => {
const [disabled, setDisabled] = useState(false);

  const controllSetStateFun = () => {
    // use the child coomponent setDisabled then I can re-render child component from Parent
  };

  return (
    <div>
     <ChildButton disabled={disabled} setDisabled={setDisabled}/>
    </div>
  );
}

CodePudding user response:

Please Define the state in Parent Component and update from the child.

const Parent = () => {
const [disabled, setDisabled] = useState(fals
  const controllSetStateFun = () => {
    // use the child coomponent setDisabled then I can re-render child component from Parent
  };

  return (
    <div>
     <ChildButton visibility ={disbales} visibilityfunction ={setDisabled} />
    </div>
  );
}


const ChildButton = (props) => {
 

  return <div onClick={props.visibilityfunction} />
}
  • Related