Home > OS >  How to have three elements in a row in React
How to have three elements in a row in React

Time:11-17

I use React and Typescript.

I want to display these three elements next to each other in a row.

With the current code, the first button is on the left, but the input form and upload button are stacked on top of each other on the right. How can I make the three elements display in a row all next to each other?

return (
<Box padding={2}>
  <Typography variant="h4">
    <FormattedMessage defaultMessage="Add file" />
  </Typography>
  <Grid container alignItems="center" spacing={2} direction="row">
    <Grid item>
      <Button
        startIcon={<Search />}
        variant="contained"
        component="label"
        disabled={rulesFromFile.isLoading}
        onClick={() => setUploadedFile(undefined)}
      >
        <FormattedMessage defaultMessage="Choose file" />
        <input
          type="file"
          hidden
          onChange={(event: ChangeEvent<HTMLInputElement>) =>
            event.target.files && setSelectedFile(event.target.files[0])
          }
        />
      </Button>
    </Grid>
    {selectedFile && (!uploadedFile || rulesFromFile.isLoading) && (
      <div>
        <Grid item>
          <form>
            <TextField
              type="text"
              size="small"
              style={{marginLeft: 4}}
              label="someNumber"
              variant="outlined"
              value={someNumber}
              onChange={e => setNumber(e.target.value)}
            />
          </form>
        </Grid>
        <Grid item>
          <LoadingButton
            startIcon={<Upload />}
            loadingPosition="start"
            variant="contained"
            color="secondary"
            style={{marginLeft: 4}}
            onClick={() => {
              selectedFile &&
                rulesFromFile.mutateAsync({
                  file: selectedFile,
                  someNumber: someNumber,
                });
              setUploadedFile(selectedFile);
            }}
            loading={rulesFromFile.isLoading}
          >
            <FormattedMessage defaultMessage="{fileName} upload" values={{fileName: selectedFile.name}} />
          </LoadingButton>
        </Grid>
      </div>
    )}
  </Grid>
</Box>

);

CodePudding user response:

Instead of a div tag, you need to use react fragment to keep items in a row

sth like this :

   {selectedFile && (!uploadedFile || rulesFromFile.isLoading) && (
      <>
      <Grid item>...</Grid>
      <Grid item>...</Grid>
     </>
  )}
  • Related