Employing an odd/even toggle for assigning class names

I need each this.state.title to be aligned based on a different classname.

I attempted using css flex boxes/nth-of-type/nth-child, but it didn't work well with React.

I'm utilizing this.state to access my objects.

My failed strategy

render: function () {
    let className
    var newVar = !someVar;

 switch(someVar) {
        case odd:
            className= "post-1 line";
            break;
        case even:
            className = "post-2 right-align line";
            break;
    }
    return (
          <article class={I WANT THIS TO FILL FROM SWITCH}>           
              <div class="s-12 l-6 post-image">                   
                 <a href="post-1.html">
                 <img src="/post1.jpg">
                 </a>                
              </div>          
              <div class="s-12 l-5 post-text">
                 <a href="#">
                    <h2>{this.state.title}</h2>
                 </a>
                 <p>Testing           
                 </p>
              </div>

              <div class="s-12 l-1 post-date">
                 <p class="date">28</p>
                 <p class="month">feb</p>
              </div>
           </article>

    );
  }
});

Answer №1

When using React, remember to rewrite the class attribute as className. For more details, check out this React documentation.

    render: function () {
        let className = ['post-2 right-align line', 'post-1 line'][someVar % 2];
        return (
            <article className={className}>
                <div className="s-12 l-6 post-image">
                    <a href="post-1.html">
                        <img src="/post1.jpg"/>
                    </a>
                </div>
                <div className="s-12 l-5 post-text">
                    <a href="#">
                        <h2>{this.state.title}</h2>
                    </a>
                    <p>Testing
                    </p>
                </div>

                <div className="s-12 l-1 post-date">
                    <p className="date">28</p>
                    <p className="month">feb</p>
                </div>
            </article>
        );
    }

Answer №2

Is the variable 'someVar' a local variable? You could attempt to include it in the component's state and update it using this.setState as needed.

Answer №3

Below is an example showcasing the entire code snippet:

        class Post extends Component {
            render() {
                let {index, title} = this.props;
                let className = ['post-2 right-align line', 'post-1 line'][index % 2];
                return <li key={index} id={index} className={className}>{title}</li>
            }
        }

        class PostList extends Component {
            render() {
                let i = 0;
                let postFactory = (props = {}) => {
                    return <Post key={i} index={i++} {...props}/>
                };
                return (<ul>
                    {this.props.posts.map((item) => postFactory({title: item}))}
                </ul>);
            }
        }

        ReactDOM.render(
            <PostList posts={['first post', 'second post', 'last post']}/>,
            document.getElementById('container')
        );

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

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

Is it feasible to exclude certain CSS files in an HTML Master page within the .NET framework?

On my website, I have 6 CSS files linked, but on a specific page, I only need to use 3 of them. Our developers are using a master page in .NET and are hesitant to make changes to it. Therefore, I am wondering if there is a way to exclude certain linked C ...

Is it possible to retrieve a value within nested objects using only a single string as the reference?

Can a value inside a nested object be accessed with a single string? For example, consider the object below: skill: { skillDetails: { developerDetails: { developerName: "mr. developer" } } } Is there a way to retrieve ...

Discovering the specific style within an inspect-element and transferring it to a JavaScript file

As a novice in the realm of react/javascript, I encountered a situation where I successfully edited a specific style using the inspect element tool. However, despite my efforts, I struggled to locate the corresponding style within the Javascript file. Ha ...

Javascript - Transforming tabular information into a hierarchical tree structure (JSON)

When extracting JSON data from a table, the format typically resembles the following simplified structure: https://i.sstatic.net/eqfXM.png The JSON format obtained might look like this: const myObjOriginal = { "rows": [{ "name": "row 1", "cell ...

Tips on displaying the number of items ordered above the cart icon

Hey there, I've been attempting to place a number in the top left corner of a cart icon without success. My goal is to achieve a result similar to the image shown here: enter image description here Here is the code snippet I've been using: < ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...

Issues with Sound Not Playing When Button is Clicked in Python Flask

My goal is to trigger an audio sound when the Delete button is clicked. I've created an external JavaScript file and successfully linked it with Flask. index.html <a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound ...

Add a unique design to a list element with CSS

I've successfully arranged a simple list in a line with a background image for all items. However, I want to have a different background image for specific list items (List item 3) without resorting to using !important. Below is the code I am currentl ...

Using Swagger with Next.js

Is it possible to generate Swagger documentation for API routes in NEXT.js? I am working with Next.js for both front-end and back-end tasks, and I am interested in creating a Swagger documentation for the APIs implemented in Next.js. ...

Ways to utilize the useRef method within the useContext hook while implementing Typescript

Struggling to incorporate useRef into my global Next.js useContext function while utilizing TypeScript. Attempted approach and encountered errors: interface tripAttributes{ tripTitle: string } const initialTripState: tripAttributes = { tripTitle ...

Develop an Innovative Data-Driven Application using AJAX Technology

After inputting an artist's name and clicking on the button, I expect to receive a visually appealing list of their songs. I am encountering the following issue: Whenever I hit the button, no results are being returned, and I am unsure of the reaso ...

Button for Selecting Colors

I love the color picker button on Google Keep, where a variety of colors pop up for selection. I'd like to add something similar to my website. What steps should I take to implement this feature? ...

What is the reason that I am unable to utilize the React and Express libraries from the global space when installed via npm i -g pkgName, yet I am able to use react-scripts from the global space?

Could there be knowledge missing that is preventing this import to work? It seems odd that we can access other globally installed modules like jest, live-server, react-scripts, http-server, but not this one. Any guidance on resolving this issue would be ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

Show specific button text when no file has been selected

I have a form with an image container that allows users to change the photo. The icon opens a file browser, and when the user selects a file, the Change button submits the photo and updates it. https://i.sstatic.net/R5vwn.jpg If no file is selected, I wa ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

Video Background, Adjusting Scale to Fit Height and Cropping Width as Necessary

Forgive me if this question has already been posed, but my search through various related discussions has not yielded the exact solution I'm looking for. My dilemma involves a 1280x720 video that I want to use as the background on my webpage. I need ...

Steps for Building and Exporting a Next.js Project Without Minification and Optimization

Is there a way to build and export a Next.js project without minifying and optimizing the output files? ...

JavaScript application throwing error: "require is not defined"

Currently, I am working on storing an array in a .json file using NodeJS. However, when trying to execute the code below, I encountered an error message saying require is not defined. Can someone provide some guidance on how to resolve this issue? let ans ...