Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch multiple react components on same page

I have a user dashboard build using material-ui list. For each listItem i have a component for it. What I want is, when I click a list element, there is a section dedicated for switching the components. I am having trouble implementing this.Here is my code.I am not sure where to put onClick handler. I will appreciate any lead. Even loggin when a particular listItem is clicked. Then I can go ahead and use react conditional rendering. In the picture below, when a user clicks All events, a component for that is rendered on the right. When MyEvents is clicked, a component for it, is rendered.

enter image description here

Code:

UserTileData.js

export const profileFolderListItems = (
  <div>
    <ListItem button>
     <ListItemIcon>
       <SendIcon />
     </ListItemIcon>
     <Badge badgeContent={3} color='primary'>
       <ListItemText primary='Events attending' />
     </Badge>
     </ListItem>
     <ListItem button>
       <ListItemIcon>
        <CreateIcon />
       </ListItemIcon>
     <ListItemText primary='New Event' />
    </ListItem>

  </div>
)

UserProfilePage.js

 class UserProfile extends Component {
  constructor (props) {
    super(props)
    this.state = {
      componentTodisplay: null

    }
  }

  render () {
    const { classes } = this.props

    return (
      <div>

        <div className={classes.root}>

          <Drawer
            variant='permanent'
            classes={{
              paper: classes.drawerPaper
            }}
          >
            <div className={classes.toolbar} />
            <List >{eventsFolderListItems}</List>
            <Divider />
            <List>{profileFolderListItems}</List>
          </Drawer>
          <main className={classes.content}>
            <div className={classes.toolbar} />
            {/* componentToDisplay goes here */}

          </main>
        </div>
      </div>
    )
  }
}

UserProfile.propTypes = {
  classes: PropTypes.object.isRequired
}

export default withStyles(styles)(UserProfile)
like image 859
Shammir Avatar asked Jun 15 '26 08:06

Shammir


1 Answers

You should use React Router (or any similar routing library).

https://github.com/ReactTraining/react-router

https://reacttraining.com/react-router/web/example/basic

In the picture below, when a user clicks All events, a component for that is rendered on the right. When MyEvents is clicked, a component for it, is rendered.

It would probably also be helpful if the user can browse to /my-events and /all-events, or bookmark them. What about when the user presses the back/forward buttons in their browser?

Using a routing library solves all of these problems (and more!) for you.

like image 104
thirtydot Avatar answered Jun 17 '26 02:06

thirtydot