Ad

Is There A Way To Separately Style Components Rendered Using The .map() Function?

- 1 answer

I am rendering one <Tuner /> component for each item in my this.state.notes array using this.state.notes.map(). I would like to know if there is a way to style each of these components separately. I would like to position them individually on the page but they are all being rendered together, so if im not mistaken, neither inline styling or className will work. How can this be done?

 this.state = {
  notes: [
    { note: "E", tone: E },
    { note: "A", tone: A },
    { note: "D", tone: D },
    { note: "G", tone: G },
    { note: "B", tone: B },
    { note: "e", tone: e }
  ]}


render() {
 const notes = this.state.notes.map(note => (
  <Tuner
    key={note.note}
    note={note.note}
  />
));

return (
  <div className="App">
    <h1>Online Guitar Tuner</h1>
    {notes}
  </div>
);


}

EDIT: I have tried a couple of the solutions that were suggested, but none of them seems to be working.

for this solution, the styles show up in the rendered component in the React console, but the actual styling is not being applied. I think maybe I'm just missing something small here, since the styles exist on the component but just aren't being applied.

constructor(props){
  this.noteStyles = {
    E: {
      backgroundColor: "#4caf50",
      border: "none",
      color: "white",
      padding: "15px 32px",
      textAlign: "center",
      textDecoration: "none",
      fontSize: "16px"
    }
  };

 this.state = {
  notes: [
    { note: "E", tone: E },
    { note: "A", tone: A },
    { note: "D", tone: D },
    { note: "G", tone: G },
    { note: "B", tone: B },
    { note: "e", tone: e }
  ]}
}

const notes = this.state.notes.map(note => (
  <Tuner
    key={note.note}
    playSound={e => this.playSound(e)}
    note={note.note}
    styles={this.noteStyles[note.note]}

  />
));
Ad

Answer

You can use predefined styles and generate them with className or inline styles but less recommended like so:

import React from 'react';
import ReactDOM from 'react-dom';
import './noteStyles.css';

const notes = [{ note: 'A' }, { note: 'B' }];

const NOTE_STYLE = {
  B: {
    color: 'pink'
  },
  A: {
    color: 'palegreen'
  }
};

const App = () => {
  return (
    <>
      {notes.map(({ note }) => (
        <div className={`noteStyle${note}`} style={NOTE_STYLE[note]}>
          {note}
        </div>
      ))}
    </>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

Edit Q-58903166-DynamicStyle

Ad
source: stackoverflow.com
Ad