Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image.

Currently, I have multiple TimelineContent elements created using .map() function, so simply using flex-direction: row-reverse won't solve the issue.

Here is a visual example of the problem: https://i.sstatic.net/6MYMD.png

  • The first TimelineContent has the text aligned to the left, which is correct.
  • The second TimelineContent has the text not aligned properly to the right.

Below is the code snippet I am currently working with:

<Timeline align="alternate">
           {result.map((index) => {
                return (
                        <TimelineItem className={classes.timelineStyle}>

                            <TimelineOppositeContent>
                                <Typography variant="body2" color="textSecondary">
                                    {index.sif_date}
                                </Typography>
                            </TimelineOppositeContent>

                                <TimelineSeparator>
                                    <TimelineDot className={classes.dot}>
                                        <LaptopMacIcon/>
                                    </TimelineDot>
                                <TimelineConnector />
                                </TimelineSeparator>

                            <TimelineContent>
                                <Paper elevation={3} className={classes.paper}>
                                    
                                    <Grid style={{display: 'flex', flexWrap: 'nowrap'}}>
                                        <Grid item>
                                            <Typography variant="h6" component="h1">
                                                {index.sif_titre}
                                            </Typography>
                                            <Typography style={{fontSize: 'smaller'}}>
                                                {index.sif_msg}
                                            </Typography>
                                        </Grid>

                                        <Grid item>
                                            <Zoom overlayBgColorStart='rgba(73, 80, 87, 67)' overlayBgColorEnd='rgba(73, 80, 87, 67)' zoomMargin={100}>
                                                <img src={index.sif_image} alt={index.sif_image} className={classes.img} style={{maxWidth: 200, maxHeight: 200}}/>
                                            </Zoom>
                                        </Grid>
                                    </Grid>

                                </Paper>
                            </TimelineContent>

                        </TimelineItem>
                )
                })
            }
        </Timeline>
const useStyles = makeStyles((theme) => ({
  paper: {
    padding: '6px 16px',
    textAlign: 'center',
    backgroundColor: 'white !important',
    display: 'flex'
    ...
}));

Edit:

Here is the full code snippet for my page:

import React from 'react';
...
export default index;

Answer №1

To achieve this effect, utilize the nth-child selector in CSS to alternate between styles and flex directions.

For more information on the nth-child selector, check out: https://developer.mozilla.org/de/docs/Web/CSS/:nth-child

.parent{
  display: flex;
  flex-directrion: row;
}

.parent:nth-child(2n+1){ /* or: :nth-child(odd) */
  flex-direction: row-reverse;
}
<div class="parent">
  <div class="img">IMG</div>
  <div class="txt">txt</div>
</div>
<div class="parent">
  <div class="img">IMG</div>
  <div class="txt">txt</div>
</div>
<div class="parent">
  <div class="img">IMG</div>
  <div class="txt">txt</div>
</div>
<div class="parent">
  <div class="img">IMG</div>
  <div class="txt">txt</div>
</div>

Answer №2

To determine if we're on an even or odd iteration, I recommend using a modulo operation. Additionally, I have defined the title component as a variable to avoid redundancy:

{result.map((index, i) => {
    
    let isEven = i % 2 === 0,
        titleComponent = (
            <Grid item>
                <Typography variant="h6" component="h1">
                    {index.sif_titre}
                </Typography>
                <Typography style={{fontSize: 'smaller'}}>
                    {index.sif_msg}
                </Typography>
            </Grid>
        );
    
    return (
        <TimelineItem className={classes.timelineStyle}>

            <TimelineOppositeContent>
                <Typography variant="body2" color="textSecondary">
                    {index.sif_date}
                </Typography>
            </TimelineOppositeContent>

            <TimelineSeparator>
                <TimelineDot className={classes.dot}>
                    <LaptopMacIcon/>
                </TimelineDot>
                <TimelineConnector />
            </TimelineSeparator>

            <TimelineContent>
                <Paper elevation={3} className={classes.paper}>

                    <Grid style={{display: 'flex', flexWrap: 'nowrap'}}>

                        {isEven && titleComponent}

                        <Grid item>
                            <Zoom overlayBgColorStart='rgba(73, 80, 87, 67)' overlayBgColorEnd='rgba(73, 80, 87, 67)' zoomMargin={100}>
                                <img src={index.sif_image} alt={index.sif_image} className={classes.img} style={{maxWidth: 200, maxHeight: 200}}/>
                            </Zoom>
                        </Grid>

                        {!isEven && titleComponent}

                    </Grid>

                </Paper>
            </TimelineContent>

        </TimelineItem>
    )
})}

For a demonstration of how the modulo operator works, you can check out this example: https://jsfiddle.net/q12yah85/

Answer №3

Let's create a custom styled timeline item in React using Material-UI:
 
const CustomTimelineItem = withStyles({
  alignAlternate: {
    "&:nth-child(even) .MuiTimelineItem-content": {
      direction: "rtl"
    }
  }
})(TimelineItem);

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

Remove the empty space between lines of images

Is there a way to remove the horizontal and vertical space between the squares? <div class="first"> <ul> <li><img src="http://dummyimage.com/40x40/111111/000000.jpg"/></li> <li><img src="http://dummyimage ...

Secure User Authentication using HTML and JavaScript Box

In the given code, I am attempting to implement a functionality where a message is displayed next to the select box if it does not have a value of male or female. This message should not be shown if one of these values is selected. However, this feature ...

Is there a way to modify the color of ASCII art letters within HTML's <pre> tags?

For this illustration, I aim to transform the letter "y" into a shade of blue. ,ggggggggggggggg dP""""""88""""""" Yb,_ 88 `"" 88 88 88 gg gg 88 I8 8I gg, 88 ...

Leveraging PHP for populating JavaScript variables

I am currently working on populating a Drop-Down menu from a csv file stored on a network share. So far, I have successfully managed to populate the options when the file is in the wwwroot folder. However, I am now encountering an issue with referencing a ...

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Tips for minimizing API calls when validating the authenticity of a JWT token stored in a cookie

Upon a user logging in through my React frontend, an API call is made to the server side to generate a JWT token which is then sent back in a secure HTTP-only cookie. Subsequent API calls from the frontend include this cookie for verification on the server ...

Experiencing difficulties in installing opensea-js using NPM

While working on my project, I encountered an issue when trying to install opensea-js as a dependency. My Node version is v14.16.0 and NPM version is v7.7.5. Every time I run the command npm install --save opensea-js, it results in an error. I attempted c ...

Failed to create a React app using npx create-react-app command

Is this error message familiar to you? The process of creating a new React app in C:\Users\ASUS\Desktop\desk\react1\my-app is running into some issues. An error occurred while installing packages. This may take some time to r ...

The error message "TypeError: Cannot access 'url' property of undefined in Strapi

I am facing an issue with a list of items where some have download links while others do not. Whenever I try to render an undefined URL, it triggers an error. To resolve this, I attempted the following: if (spectacle.pdf.url) { const pdf = spectacle.p ...

Error TS2488 in React TypeScript: The data type 'IStateTypes' is required to have a method called '[Symbol.iterator]()' that returns an iterator

At the moment, I am working on implementing a global state in React Hooks but have run into an issue. https://i.stack.imgur.com/DN83K.png The current problem I'm facing is with [Symbol.iterator](. I am uncertain about how to resolve this as I am in ...

Navigating dropdown list items using the keyboard in TypeScript is a breeze

I've encountered a bug while working on my open-source project. The issue is with navigating the dropdown list items using the keyboard (arrow key/tab). I have implemented the keyboard-navigation logic, but I'm unsure of how to make it work corre ...

The mobile-responsive dropdown navigation bar functions well on browsers with small widths, but does not work properly on my phone

I am experiencing an issue with the mobile responsive dropdown navigation bar on my website. It works perfectly fine on a small width browser, but when I try to open it on my phone, nothing happens. This is puzzling me as I am new to making websites respon ...

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...

How can I invoke a function within a directive-generated HTML element's scope?

I created a custom directive that utilizes element.html() to set the HTML content. Within this HTML code, I would like to be able to invoke functions from the scope where the directive is being used. Here's an example: app.directive('myDirective ...

Tips for ensuring that the horizontal scroll bar remains consistently positioned at the bottom of the screen

There are two div sections on a page, with one positioned on the left and the other on the right. The div on the right contains multiple dynamically generated tags which necessitate a horizontal scroll bar (overflow:auto). This causes the div's height ...

Choose a HTML element <a> containing a hyperlink reference and a nested child element <li>

Does anyone know of a way in javascript/css to select the (n) <li> in my code, while also specifying that the <li> must have a parent with the current <a> tag containing a specific href link? <a href="www.link.com">CATEGORY NAME& ...

Module for Node.js that handles .ini files where variable names can begin with a number

.ini file: [1] 10X=true [2] 10X=true node.js : var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/MS.ini', 'utf-8')); console.log(mS.1.10X); I am utilizing the ini module in node.js, which can be found at this link: https://www.n ...

Error: The mapStateToProps function in React+Redux is returning an undefined

Here's the issue I'm facing: Inside index.js: import {getShowsHome} from './reducers/reducers'; const store = createStore(getShowsHome); ReactDOM.render(<Provider store={store}> <App /> </Provider>, document.getElem ...