Home > OS >  Enable and disable buttons from a switch from different file
Enable and disable buttons from a switch from different file

Time:11-24

I'm new to react and front development any help would be appreciate, please don't make stack overflow a toxic place, laughing or closing the tick you think it is too simple or stupid. No question is stupid

A Button is stored in file panel.tsx a Switch is located in notes.tsx file the enable and disable status of the button is decided by the switch condition in the notes.tsx file.

The following code is a simplified version of the issue described above

# notes.tsx
export const AddNotes: React.FC = () => {
    const [skipNotes, setSkipNotes] = useState(false);
    const onSkipNotes = (checked: boolean) => setSkipNotes(checked);
 
    return (
        <div>
            <CC.ToggleSwitch checked={skipNotesAndTags} onChange={onSkipNotes} label="Skip notes" changeHighlight />
        </div>
    );
};


# panel.tsx
export const Panel: React.FC = () => {
  <div>
      <CC.Button text={'Submit'} disabled={true}/> // How can I disabled/enable it based on skipNotes from note.tsx
  </div>

How can I disabled/enable the Button based on skipNotes from notes.tsx?

CodePudding user response:

You need to lift the state. If you read over that section of the docs I linked, it should make sense; they explain it really well.

But just to try and explain, the useState hook for skipNotes should be placed in the common parent of notes and panel. Then you pass skipNotes and setSkipNotes in as props.

export const App: React.FC<Props> = ({}) => {
  const [skipNotes, setSkipNotes] = useState(false)
  return <>
    <AddNotes skipNotes={skipNotes} setSkipNotes={setSkipNotes} />
    <Panel skipNotes={skipNotes} />
  </>
}



export const AddNotes: React.FC = (skipNotes, setSkipNotes) => {
  const onSkipNotes = (checked: boolean) => setSkipNotes(checked)
  return (
    <div>
      <CC.ToggleSwitch checked={skipNotes} onChange={onSkipNotes} label="Skip notes" changeHighlight />
    </div>
  )
}


export const Panel: React.FC = (skipNotes) => {
  return (
    <div>
      <CC.Button text="Submit" disabled={skipNotes}/>
    </div>
  )
}

CodePudding user response:

there are couple solutions for your question

  1. to globalize your state and the simplest way is by using useContext hook
  2. or just simply pass the state as props from a parent component to its child here is a react js example (instead of ts I hope that's fine) of how it's done link
  • Related