简体   繁体   中英

How to get a state from a different component in React

I need to disable a button in reactjs depending on a value taken from a different component.

In below component ( main.js ), I need to disable the Button. But This has to be disabled depending on a value taken from a value another component ( upload.js )

export default function HorizontalLabelPositionBelowStepper() {
  .
  .
  .
  return (
    <Grid container>      
      <Grid item lg="12" md="12" xs="12">
          <div className={classes.root}>                   
                <div>
                  <Grid container justify="center">                                      
                    <Grid item md="1">
                      <Button // button I need to disable
                        variant="contained"
                        color="secondary"
                        onClick={handleNext}
                        endIcon={<NavigateNext />}
                      >
                        {activeStep === steps.length - 1 ? "Finish" : "Next"} 
                      </Button>
                    </Grid>
                  </Grid>
                </div>                         
          </div>
      </Grid>
    </Grid>
  );
}

And this is the upload.js

// imports...
.
.
.

export default function ElevateAppBar(props) {
  const [file, setFile] = useState('');
  const [filename, setFileName] = useState('eg: employees.csv'); // this filename value should be passed to the component `main.js`

  return (
    <Grid container justify="flex-start">
      <Grid container item lg="12" md="12">        
        <Grid item lg="4" md="4" xs="4">
          <Form>
            <Form.File id="custom-file" label={filename} custom />
          </Form>
        </Grid>
      </Grid>      
      <Grid container justify="center">
        <Button variant="contained" style={{backgroundColor: "lightgreen"}} endIcon={<CloudUpload />}>
          Upload
        </Button>
      </Grid>
    </Grid>
  );
}

In the upload.js I have a variable with the name filename . I need to pass this value to the first component - that is main.js

so the logic could be like something (this is not reactjs syntaxes, this is just to give the idea on what I need to do):

if(filename_taken_from_upload_js == "eg: employees.csv"){
  // disable the button
}else{
  // enable the button
}

Can someone help, Please?

This could be a case for lifting state up:https://reactjs.org/docs/lifting-state-up.html#lifting-state-up

If this value could be used by other unrelated components, you should consider putting it in a global state, using Redux or Context API.

https://redux.js.org/faq/react-redux#react-redux https://reactjs.org/docs/context.html#when-to-use-context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM