Search code examples
reactjsdictionaryobjectclassname

How to add className to list from map array depending on object value


I am trying to add className value to list items. I map through an array of objects, and depending on the value of 'name' in the object, a differenct class would be added.

Specifically, I am trying to make a message app, if the user is 'You', the message would have class 'right' and the message is shown on the rihgt of the screen. If the user name != 'You', then the className 'left' should be given.

I've tried adding an if statement within the render part of the code, and also within the sendMessage() function to add the class when pushing the message into the array (before it is even shown on the screen). All I get are syntax errors. Please advise...

import React, { Component } from 'react';

class LandingPage extends Component {
  constructor(props) {
    // When you pass props to super, the props get assigned to 'this'
    super(props);
    // this.state is the buildiing block of the data that gets used
    this.state = {
      message: '',
      name: '',
      list: []
    }
  }

  updateInput(key, value) {
    // update react state with input data
    this.setState({
      [key]: value
    })
  }

  sendMessage() {
    const newMessage = {
      message: this.state.newMessage,
      name: 'You'
    }

    const list = [...this.state.list];

    list.push(newMessage);

    this.setState({
      list,
      newMessage: ''
    })
  }

  render() {
    return <div className='container'>

      {/* messages will be listed here */}
      <div className='messagesDiv'>
        <ul>
          {/* List array is mapped through*/}
          {this.state.list.map(item => {
            return (
              <li className={item.class}>
                {item.name}: {item.message}
              </li>
            )
          })}
        </ul>
      </div>

      {/* message text area and send button here  */}
      <div className='inputDiv'>
        <form>
          <input type='text' className='input'
            value={this.message}
            onChange={e => this.updateInput('newMessage', e.target.value)}
          />
          <button className='btn btn-primary'
            onClick={() => this.sendMessage()}>Send</button>
        </form>
      </div>

    </div>
  }
}
export default LandingPage;

So above where it has {item.class}, this should either be 'right' or 'left'.

I've left just the code I think you'd need to see to diagnose my problem/ offer a solution.

Thanks.


Solution

  • You could use a simple function like this:

    function userToClass(user){
       var userClass = '';
       if(user === 'You') {
          userClass = 'left';
       }
       else 
          userClass = 'right';
       }
    
       return userClass ;
    }
    

    and then use it like this:

    return (
              <li className={userToClass(item.name)}>
                {item.name}: {item.message}
              </li>
            )