Create a React component using Material UI that remains fixed at the top of the page when scrolling, without being

My AppBar is working fine without using sticky, but I need the element on my page to stick at the top when the user scrolls. I found a solution that seems to work here: https://www.w3schools.com/howto/howto_css_sticky_element.asp

However, in my React page, I want my ProgressBar component to remain at the top. The RenderTeamSelections component, which is a large table below it, quickly pushes the ProgressBar out of view. I want the ProgressBar to stay visible while the user interacts with the table. Here is the relevant code:

return (
      <div className={rootClassName}>
        <div className="g-row">
          <div className="g-col">
            <AccountProfile {...this.props} />
            <br />
            <Team team={this.props.team} profileDetail={profileDetail} />
            <br />
            <ProgressBar {...this.props} />
            <br />
            <RenderTeamSelections {...this.props] />
          </div>
        </div>
      </div>
    );

I have tried using withStyles and experimenting with 'fixed', 'sticky', and '-webkit-sticky' for the position of the ProgressBar, but it has not stayed at the top when scrolling. Any assistance would be greatly appreciated as I could not find any direct solutions in the Material docs for this scenario.

Answer №1

For most components, you can apply the CSS property {position: 'fixed'}. If this does not work, consider adjusting the zIndex.

Here is an example:

<Paper style={{position: 'fixed'}}>
   <List className={classes.list} component="nav" aria-label="main mailbox folders"
      subheader={<ListSubheader component="div" id="nested-list-subheader">Navigation</ListSubheader>}>
          <ListItem button>
             <ListItemIcon>
               <SubjectIcon/>
             </ListItemIcon>
             <ListItemText primary="Overview" />
          </ListItem>
  </List>

Answer №2

I managed to successfully implement material ui themes to get it working.

Below are the custom styles I used in my component. I included a z-index property to address an issue where my table selects and header data were still visible when scrolling through

<RenderTeamSelections {...this.props] />
.

Here is the final version of the component with the applied styles:

const styles = theme => ({
    root: {
        background: 'white',
        position: '-webkit-sticky',
        position: 'sticky',
        top: 20,
        bottom: 20, 
        paddingTop: '40px',
        paddingBottom: '40px',
        zIndex: 5,
    },
    details: {
        display: 'flex'
    },
    progressWrapper: {
        marginTop: theme.spacing(2)
    },
    linearProgress: {
        height: 20
    },
});


export function ProgressBar(props) {
    const { profileDetail, classes } = props;
    const [completeness, setCompleteness] = useState(0)

    useEffect(() => {
        if (profileDetail) {
            setCompleteness(profileDetail.teamKeysTier1.split(",").filter(x => { return x.length != 0 }).length + profileDetail.teamKeysTier2.split(",").filter(x => { return x.length != 0 }).length)
        }
    }, [profileDetail])

    return (
        <Portlet className={classes.root} >
            <PortletContent >
                {completeness > 8 ?
                    <div className={classes.progressWrapper}>
                        <Typography variant="h3" color="textSecondary">Team Selection Completeness: {completeness * 10 + 10}%</Typography>
                        <br /> 
                        <br />
                        <LinearProgress
                            className={classes.linearProgress}
                            value={completeness * 10 + 10}
                            variant="determinate"
                            position="fixed"
                        /> </div> :
                    <div className={classes.progressWrapper}>
                        <Typography variant="h3" color="textSecondary">Team Selection Completeness: {completeness * 10}%</Typography>
                        <br /> 
                        <br />
                        <LinearProgress
                            className={classes.linearProgress}
                            value={completeness * 10}
                            variant="determinate"
                            position="fixed"
                        />
                    </div>}
            </PortletContent>
        </Portlet>

    )

}

export default withStyles(styles)(ProgressBar);

Answer №3

For a fixed placement, you can utilize the Material UI AppBar component and set the position attribute to "sticky".

<AppBar position="sticky"></AppBar>

Check out more at this link!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to resolve the 'form' variable being assigned a value but never used in axios:

I am encountering an issue with a contact form that utilizes React with axios on the frontend and Express with nodemailer on the backend while running locally. The expected outcome is for me to receive an email when I click the "Submit" button. However, up ...

Should I make the API call from the node server or from React on the client side?

I attempted to fetch data from a government website API to retrieve information about COVID-19 vaccine availability in a specific pin code. I wrote a function with the API call in a file named searchbypinapi.js and then imported and executed this function ...

the react package fails to meet the expectations of its fellow components

Encountering the same error repeatedly while trying to deploy on Galaxy or execute any meteor command. I've attempted various solutions like deleting the npm-container folder and re-adding meteorhacks:npm, but unfortunately, none of them have worked. ...

Utilizing React JS with Material-UI Autocomplete allows for seamlessly transferring the selected item from the renderInput to the InputProps of the textfield component

Exploring the functionality of the updated version of Autocomplete, my goal is to ensure that when an element is chosen from the dropdown menu, the input format of the text field will be modified to accommodate adding a chip with the selected text. Is the ...

Issues with the performance of input range sliders in iOS Safari is causing frustration

I recently developed a basic range slider component for an application built with NextJS. This component utilizes an <input type="range"> element. While the range slider functions properly on Desktop and Android devices, I encountered sign ...

Analyzing Passwords for Redirection

Greetings to all! I trust everyone is doing well. I have developed a react application that features 2 password fields, each with validation using regular expressions. Upon successful validation of both passwords, the application will automatically redirec ...

Having trouble with Next.js generateStaticParams function not producing the desired output

My goal is to create a simple webpage using Next.js that allows me to select an event from a list and view its details on a new page by clicking on it. The main focus for now is just displaying the event ID. However, when I try to build the project with y ...

What is the best way to submit several files along with additional fields simultaneously using FormData?

I have a collection called pocketbase that consists of fields like name, image, and order. My goal is to upload all the images with unique names and in parallel using the power of FormData. Take a look at my code below: export default function AddPhotosAd ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

React, managing states with multiple options for a property's state

Let's say I have a state set up like this: this.state = {status: 'disconnected'} How should I handle the different possible values for status, such as 'disconnected', 'connected', or 'connecting'? Is it best p ...

Can passing parameters between nested map functions cause any issues?

While attempting to navigate to a page in reactjs and pass parameters using the useNavigate hook, I encounter an unexpected token error as soon as I include the navigation within the anchor tag. <a onClick={() ={ ...

Is AngularJS causing issues with Foundation modals? Any solutions to this problem?

Wondering how to manage Foundation4 modals with AngularJS? I've noticed that when I navigate from a modal to a new view, the old modal disappears but the page stays darkened as if it's still there in the background. I tried adding a class attribu ...

Unique approaches: Custom layouts compared to a single adaptive layout for managing various device sizes and orientations

When designing layouts for desktop, tablet, and smartphone in both portrait and landscape orientations within a Single Page Application, is it more effective to separate the layouts as different resources and load them dynamically based on device detection ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

You may only insert a single image into a container

My goal is to display two images side by side with text centered between them. However, when I add the first image using CSS and the background property, I run into issues adding a second image as it overrides the first one. Placing the images directly in ...

Enforcing HTTPS in Next.js version 13

I've encountered a challenge while working with Next.js 13 and Heroku - there seems to be limited information on handling SSL with this combination. Although I have implemented a solution derived from this blog post below, Google is not happy with the ...

Styling with CSS: I am looking to display images beneath text

I am facing a challenge with displaying an image within a container. The container has a background image with the position set to relative and contains some text. I would like to display another image within this container, with the position set to absolu ...

Remove the image from the container in Bootstrap

I'm looking to position an image outside the container so that the right margin remains within the default container width (responsive) while keeping the image aligned with a button consistently. Please refer to the image below for clarification: ht ...

When working with Web Workers in Jest, you may encounter an error stating "Cannot use 'import.meta' outside a module."

I'm currently developing a web application using nextjs 10.1.3. To improve performance, we have integrated a web worker on one of the pages and intend to add more workers in the future. All our code is thoroughly unit tested, and with the use of the w ...

Enhance your design with dynamic hover effects

I need assistance with modifying the menu structure generated by Wordpress. Specifically, I want to change the background of #header-nav li ul.children li a when #header-nav li ul.children li ul.children li a:hover is active. Could someone provide guidanc ...