Is There A Way To Separately Style Components Rendered Using The .map() Function?
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]}
/>
));
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'));
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM