react counter for each item of list - reactjs

I'm trying to create a counter for each item in a list in React. I want each to be incremented or decremented individually depending on what the user clicks on. This issue is that all counters increment and decrement on click
of a single element, but I would like only the clicked element's counter to change.
this is my code:
class name extends Component {
constructor(){
super()
this.state = {
news: [],
voteing: 0
}
}
onVoting(type){
this.setState(prevState => {
return {voteing: type == 'add' ? prevState.voteing + 1: prevState.voteing- 1}
});
}
render() {
return (
<React.Fragment>
<Content>
{
this.state.news.map((item, i)=>{
return (
<Item key={i}>
<text>
{item.subject}
{item.details}
</text>
<Votering>
<img src="" onClick={this.onVoting.bind(this, 'add')} />
<div value={this.state.voteing}>{this.state.voteing}</div>
<img src="" onClick={this.onVoting.bind(this, 'min')} />
</Votering>
</Item>
)
})
}
</Content>
</React.Fragment>
)
}
}
I'm trying to do this:
<img src="" onClick={this.onVote(i).bind(this, 'add')} />
but it doesn't work also tried this.onVote(item.i) and same result

I cannot really see how you would like to see voting as part of the local component state, as it really has to do (in my opinion), with the entities on which you can vote.
So if I were you, I would rewrite the code slightly different. As I do not know what you intend to do afterwards with the votes (this rather assumes like a live process, or at least a kind of save button, as it is saved here in the local VotingApp state), I just save everything to the local state, how you would handle that is not really my intend to answer.
So personally, I would rather go for one functional component, just rendering the news item and it's voting capability, where the voteCount is part of the item entity. If this is not how you receive the data, nothing stops you from adding the data after your fetch and before really showing it on the screen. The app itself will receive the changes and the item that will be changed, and what it does there-after, would be all up to you ;)
const { Component } = React;
const NewsItem = ( item ) => {
const { subject, details, voteCount, handleVoteChange } = item;
return (
<div className="news-item">
<div className="news-vote">
<div className="vote-up" title="Vote up" onClick={ () => handleVoteChange( item, 1 ) }></div>
<div className="vote-count">{ voteCount }</div>
<div className="vote-down" title="Vote down" onClick={ () => handleVoteChange( item, -1 ) }></div>
</div>
<div className="news-content">
<h3>{ subject }</h3>
<div>{ details }</div>
</div>
</div>
);
};
class VotingApp extends Component {
constructor( props ) {
super();
this.handleVoteChange = this.handleVoteChange.bind( this );
// by lack of fetching I add the initial newsItems to the state
// and work by updating local state on voteChanges
// depending on your state management (I guess you want to do something with the votes)
// you could change this
this.state = {
newsItems: props.newsItems
};
}
handleVoteChange( item, increment ) {
this.setState( ( prevState ) => {
const { newsItems } = prevState;
// updates only the single item that has changed
return {
newsItems: newsItems
.map( oldItem => oldItem.id === item.id ?
{ ...oldItem, voteCount: oldItem.voteCount + increment } :
oldItem ) };
} );
}
render() {
const { newsItems = [] } = this.state;
return (
<div className="kiosk">
{ newsItems.map( item => <NewsItem
key={ item.id }
{...item}
handleVoteChange={this.handleVoteChange} /> ) }
</div>
);
}
}
// some bogus news items
const newsItems = [
{ id: 1, voteCount: 0, subject: 'Mars in 2020', details: 'Tesla will send manned BFR rockets to Mars in 2020' },
{ id: 2, voteCount: -3, subject: 'Stackoverflow rocks', details: 'Stackoverflow is booming thanks to the new friendly policy' },
{ id: 3, voteCount: 10, subject: 'DS9: Healthy living', details: 'Eat rice everyday and drink only water, and live 10 years longer, says Dax to Sisko, Sisko suprises her by saying that like that, he doesn\'t want to live 10 years longer...' }
];
// render towards the container
const target = document.querySelector('#container');
ReactDOM.render( <VotingApp newsItems={ newsItems } />, target );
.kiosk {
display: flex;
flex-wrap: no-wrap;
}
.news-item {
display: flex;
justify-content: flex-start;
width: 100%;
}
.news-vote {
display: flex;
flex-direction: column;
align-items: center;
padding-left: 10px;
padding-right: 10px;
}
.news-vote > * {
cursor: pointer;
}
.news-content {
display: flex;
flex-direction: column;
}
.vote-up::before {
content: '▲';
}
.vote-down::before {
content: '▼';
}
.vote-up:hover, .vote-down:hover {
color: #cfcfcf;
}
h3 { margin: 0; }
<script id="react" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script id="react-dom" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<script id="prop-types" src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script id="classnames" src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.5/index.js"></script>
<div id="container"></div>

The reason all your items' counts change when any of them is clicked on is that they all share the same vote count value, voteing in the name component's state.
To fix this, you should break each item into its own stateful component. So that each can track its own click count.
For example:
class name extends Component {
constructor(){
super();
this.state = {
news: []
}
}
render() {
return (
<React.Fragment>
<Content>
{
this.state.news.map((item, i) => {
return <NewsItem key={ i }
subject={ item.subject }
details={ item.details }
/>
})
}
</Content>
</React.Fragment>
)
}
}
class NewsItem extends Component {
constructor() {
super();
this.state = {
voteCount = 0
}
}
handleVote(type) {
this.setState(prevState => ({
voteCount: type === "add" ? prevState.voteCount + 1 : prevState.voteCount - 1
}));
}
render() {
const { subject, details } = this.props;
const { voteCount } = this.state;
return (
<Item>
<text>
{ subject }
{ details }
</text>
<Votering>
<img src="" onClick={ this.handleVote.bind(this, 'add') } />
<div value={ voteCount }>{ voteCount }</div>
<img src="" onClick={ this.handleVote.bind(this, 'min') } />
</Votering>
</Item>
)
}
}
You could also maintain separate counts for each item within the parent component, but I find breaking into separate components to be much cleaner.

A few things I noticed unrelated to your question.
1) onVoting should be bound in your constructor or use onVoting = () => { ..... }
2) in your render function you have onVote instead of onVoting
On to your main question, in your state you are only maintaining one counter that is displayed and changed for all news elements. an easy way to get around this is to create a new react element for each news article that will handle the voting for each article.
class parent extends Component {
constructor(){
super()
this.state = {
news: null,
}
}
componentDidMount() {
// fetch data from api and minipulate as needed
this.setState({news: dataFromApi})
}
render() {
return (
<Content>
{
this.state.news.map((item, i)=>{
return (
<NewChildComponent data={item}/>
)
})
}
</Content>
)
}
}
class NewChildComponent extends Component {
constructor() {
super()
this.state = {
voting: 0,
}
}
onVoting = (e) => {
this.setState(prevState => ({
voteCount: e.target.name === "add" ? prevState.voteCount + 1 : prevState.voteCount - 1
}));
}
render () {
const {data} = this.props;
return (
<Item key={data.uniqueID}>
<text>
{data.subject}
{data.details}
</text>
<Votering>
<img src="" onClick={this.onVoting} name="add"/>
<div value={this.state.voteing}>{this.state.voteing}</div>
<img src="" onClick={this.onVoting} name="min"/>
</Votering>
</Item>
)
}
}
A little background on why you should not bind in your render function. https://medium.freecodecamp.org/why-arrow-functions-and-bind-in-reacts-render-are-problematic-f1c08b060e36
Here’s why: The parent component is passing down an arrow function on
props. Arrow functions are reallocated on every render (same story
with using bind). So although I’ve declared User.js as a
PureComponent, the arrow function in User’s parent causes the User
component to see a new function being sent in on props for all users.
So every user re-renders when any delete button is clicked. 👎
Also why you should not use an index as a key in React.
https://reactjs.org/docs/lists-and-keys.html
We don’t recommend using indexes for keys if the order of items may
change. This can negatively impact performance and may cause issues
with component state. Check out Robin Pokorny’s article for an
in-depth explanation on the negative impacts of using an index as a
key. If you choose not to assign an explicit key to list items then
React will default to using indexes as keys.
Here is an in-depth explanation about why keys are necessary if you’re
interested in learning more.

Related

How to pass an onMouseEnter function into child component

I would like to update my parent component's state when hovering over a child component. Basically, this parent component consists of an h1 and four components called Box. Each component has a title prop, which the component renders internally. What I would like to have happen is when a user hovers over a Box, the hovered state of the parent component changes to the title of the hovered child. Here is essentially what I have right now:
class Home extends React.Component {
constructor(props) {
super(props)
this.state = {
hovered: 'none'
};
this.handleHover = this.handleHover.bind(this);
}
handleHover = (n) => {
this.setState((n) => ({
hovered: n
}));
};
handleHoverOut = () => {
this.setState(() => ({
hovered: 'none'
}));
};
render() {
return (
<h1 className={this.state.hovered} >TITLE TITLE TITLE</h1>
<Box oME={ this.handleHover } oML={ this.handleHoverOut } title='Title1'/>
<Box oME={ this.handleHover } oML={ this.handleHoverOut } title='Title2'/>
<Box oME={ this.handleHover } oML={ this.handleHoverOut } title='Title3'/>
<Box oME={ this.handleHover } oML={ this.handleHoverOut } title='Title4'/>
)
}
class Box extends React.Component {
render() {
return(
<section onMouseEnter={() => { this.props.oME(this.props.title)}} onMouseLeave={() => { this.props.oML()}}>
...
</section>
}
I know this might not be 100% the way to go about it, but I think I'm somewhat on the right track! Please help me try to improve my code here, since I'm still learning the basics of React!
I created codesendbox where you can check the solution.
There were couple of issues in your code that I fixed there. Your state was not being displayed properly as title and there were unneeded callback functions.

How to structure React code with Apollo Query so that a random queried array of objects doesn't rerender with state change?

The problem: I'm using Apollo Client, and have the deck rendered like this "/deck/2" and I want to randomly shuffle the cards, and display just one at a time with a button to view the next. I keep running in the problem with React re-rendering everytime the state is changed (my onClick index counter +1), which reshuffles the cards since the shuffledCards variable is inside the query. I'm not sure how to prevent this from happening.
How can I shuffle the list without worrying about them being reshuffled 'onClick' of the button. I imagine there is a way to get the randomized array outside of the render, which I can do in Regular react, but using Apollo queries I'm stumbling to understand.
This is where I am stumbling due to my inexperience in React and Graphql with Apollo, and I haven't found a similar Apollo graphql project to lean off of. I can't use map on an object, but maybe there is a way to use map to display 1 object of the array at a time? I haven't found a working solution.
What I intend to have happen: I simply want to render the shuffled array of cards one at a time, and pressing the next button should step through the cards in the randomized array, without re-rendering whenever I click the button, otherwise cards will be repeated at random.
Here's the code:
import React, { Component, Fragment } from "react";
```
import CardItem from "./CardItem";
const CARDS_QUERY = gql`
query CardsQuery($id: ID!) {
```
`;
export class Cards extends Component {
constructor(props) {
super(props);
this.state = {
index: 0
};
this.goToNext = this.goToNext.bind(this);
}
goToNext() {
this.setState({
index: this.state.index + 1
});
}
shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
render() {
let { id } = this.props.match.params;
id = parseInt(id);
return (
<Fragment>
<Query query={CARDS_QUERY} variables={{ id }}>
{({ data, error, loading }) => {
if (loading) {
return <Loading />;
}
if (error)
}
const CardsToRender = data.deck.cards;
//This variable gets reshuffled at every re-render
const shuffledCards = this.shuffle(CardsToRender);
//Single item to be returned
const item = shuffledCards[this.state.index];
if (this.state.index >= shuffledCards.length) {
return (
<div>
<h1>Finished</h1>
</div>
);
} else {
return (
<Fragment>
// Here I can get one item to display, but if I press next, the state changes which fires a re-render,
//shuffling the cards once more. My intention is to only shuffle cards at first render until the browser page is
//refreshed or user navigates away
<h1>{item.front}</h1>
<h1>{item.back}</h1>
//My second attempt is to map out the cards, but I have only been able to render a list,
// but not one at a time. Maybe there is a simple code solution in my .map to display
//one at a time without needing to change state?
{shuffledCards.map(card => (
<CardItem key={card.id} card={card} />
))}
<p>
<button onClick={this.goToNext}>Next</button>
</p>
</Fragment>
);
}
}}
</Query>
</Fragment>
);
}
}
```
I'll be grateful for any help provided. Thank you!
I am not aware of Appolo Query but the issue you mentioned is more related to React. You can try below one to avoid shuffling cards on each re-render.
Refactor your component into two parts.
1) ShuffleCards.js(give any name as you like :) ) - Move your component into "ShuffleCards" and pass shuffled cords to the child component where you can update the state to render the next card.
// ShuffledCards.js
import React, { Component, Fragment } from "react";
```
import CardItem from "./CardItem";
const CARDS_QUERY = gql`
query CardsQuery($id: ID!) {
```
`;
export class ShuffleCards extends Component {
constructor(props) {
super(props);
}
shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
render() {
let { id } = this.props.match.params;
id = parseInt(id);
return (
<Fragment>
<Query query={CARDS_QUERY} variables={{ id }}>
{({ data, error, loading }) => {
if (loading) {
return <Loading />;
}
if (error) {
}
const CardsToRender = data.deck.cards;
const shuffledCards = this.shuffle(CardsToRender);
return (
<Cards shuffledCards={shuffledCards} />
);
}}
</Query>
</Fragment>
);
}
}
Move the code which handles the displaying card and updating the state to the "Cards" component.
import React, { Component, Fragment } from "react";
import CardItem from "./CardItem";
export class Cards extends Component {
constructor(props) {
super(props);
this.state = {
index: 0
};
this.goToNext = this.goToNext.bind(this);
}
goToNext() {
this.setState({
index: this.state.index + 1
});
}
render() {
const {shuffledCards} = this.props || [];
return (
<div>
{
this.state.index >= shuffledCards.length ?
<div>
<h1>Finished</h1>
</div>
:
<Fragment>
<h1>{item.front}</h1>
<h1>{item.back}</h1>
{
shuffledCards.map(card => (
<CardItem key={card.id} card={card} />
))
}
<p>
<button onClick={this.goToNext}>Next</button>
</p>
</Fragment>
}
</div>
)
}
}
You are calling this.shuffle() in your render function - therefore it will shuffle on each render.
Move that to your constructor and it will only get called once.
constructor(props) {
super(props);
this.state = {
index: 0
};
this.goToNext = this.goToNext.bind(this);
const CardsToRender = data.deck.cards;
}

How to scroll to bottom when props changed in react-virtualized?

I have component App with List from react-virtualized library.
And I need on initial render, that my List scroll to bottom.
And I did it, when added scrollToIndex option. But when I add new object in my list array, it does not scroll to my last added object. How can I fix it? And is it good solution to use "forceUpdate()" function?
import { List } from "react-virtualized";
import loremIpsum from 'lorem-ipsum';
const rowCount = 1000;
const listHeight = 600;
const rowHeight = 50;
const rowWidth = 800;
class App extends Component {
constructor() {
super();
this.renderRow = this.renderRow.bind(this);
this.list = Array(rowCount).fill().map((val, idx) => {
return {
id: idx,
name: 'John Doe',
image: 'http://via.placeholder.com/40',
text: loremIpsum({
count: 1,
units: 'sentences',
sentenceLowerBound: 4,
sentenceUpperBound: 8
})
}
});
}
handle = () => {
this.list = [...this.list, { id: 1001, name: "haha", image: '', text: 'hahahahahaha' }];
this.forceUpdate();
this.refs.List.scrollToRow(this.list.length);
};
renderRow({ index, key, style }) {
console.log('____________', this.list.length);
return (
<div key={key} style={style} className="row" >
<div className="image">
<img src={this.list[index].image} alt="" />
</div>
<div onClick={this.handle}>{this.state.a}</div>
<div className="content">
<div>{this.list[index].name}</div>
<div>{this.list[index].text}</div>
</div>
</div>
);
}
render() {
return (
<div className="App">
<div className="list">
<List
ref='List'
width={rowWidth}
height={listHeight}
rowHeight={rowHeight}
rowRenderer={this.renderRow}
rowCount={this.list.length}
overscanRowCount={3}
scrollToIndex={this.list.length}
/>
</div>
</div>
);
}
}
export default App;
You mentioning you need to scroll to the bottom when the list item is changed and to be honest i don't like to use forceUpdate. As mentioned on the React docs:
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
Luckily, one of React lifecycle method is suitable for this case, it is call componentDidUpdate. But you need to do some refactor of your code. Instead using private field, i suggest to put it on state/props.
This method will invoked immediately after updating props/state occurs. However, This method is not called for the initial render.
What you need to do is, compare the props, is it change or not? Then call this.refs.List.scrollToRow(this.list.length);
Sample code
class App extends Component {
constructor() {
this.state = {
list: [] // put your list data here
}
}
// Check the change of the list, and trigger the scroll
componentDidUpdate(prevProps, prevState) {
const { list } = this.state;
const { list: prevList } = prevState;
if (list.length !== prevList.length) {
this.refs.List.scrollToRow(list.length);
}
}
render() {
// usual business
}
}
more reference for React lifecyle methods:
https://reactjs.org/docs/react-component.html#componentdidupdate

Rendering in react with array.map

I have an array of strings which I would like to render as a list, with a colored text. The user can change the color with a button.
For that I have built a component called which receives an array and renders a list with the array's values and a button to change the color:
import React, { Component } from "react";
const renderArray = arr => (arr.map(value => (
<li>
{value}
</li>
)))
class List extends Component {
constructor(props) {
super(props);
this.state = {
color: 'red'
}
}
toggleColor = () => {
if (this.state.color === "red") {
this.setState({color: "blue"});
} else {
this.setState({color: "red"});
}
}
render() {
const style = {
color: this.state.color
};
return (
<div style={style}>
<ul>
{renderArray(this.props.array)}
</ul>
<button onClick={this.toggleColor}>Change color</button>
</div>
);
}
}
export default List;
The List is called with:
<List array={arr} />
And arr:
const arr = ['one', 'two', 'three'];
Fiddle here: Fiddle
But this seems incorrect to me. I rerender the whole array by calling renderArray() each time the color changes. In this case it is not too bad but what if the renderArray() is much more complex?
To my understanding, I need to create a new list only if the array prop changes and this could do in getDerivedStateFromProps (or in componentWillReceiveProps which will be deprecated...):
componentWillReceiveProps(nextProps)
{
const renderedArray = renderArray(nextProps.array);
this.setState({ renderedArray });
}
And then, on render, use this.state.renderedArray to show the list.
But this seems strange, to store a rendered object in the state...
Any suggestions?
Thanks!
1) React uses the concept of virtual DOM to calculate the actual difference in memory and only if it exists, render the difference into DOM
2) You can "help" React by providing a "key", so react will better understand if it's needed to re-render list/item or not
3) Your code componentWillReceiveProps can be considered as a bad practice because you're trying to make a premature optimization. Is repaint slow? Did you measure it?
4) IMHO: renderArray method doesn't make sense and can be inlined into List component
React render the DOM elements efficiently by using a virtual DOM and checks if the update needs to happen or not and hence, it may not be an issue even if you render the list using props. To optimise on it, what you can do is to make use of PureComponent which does a shallow comparison of state and props and doesn't cause a re-render if nothing has changed
import Reactfrom "react";
const renderArray = arr => (arr.map(value => (
<li>
{value}
</li>
)))
class List extends React.PureComponent { // PureComponent
constructor(props) {
super(props);
this.state = {
color: 'red'
}
}
toggleColor = () => {
if (this.state.color === "red") {
this.setState({color: "blue"});
} else {
this.setState({color: "red"});
}
}
render() {
const style = {
color: this.state.color
};
return (
<div style={style}>
<ul>
{renderArray(this.props.array)}
</ul>
<button onClick={this.toggleColor}>Change color</button>
</div>
);
}
}
export default List;

Redux: making sharing component trigger unique redux path depends on parent component

Here is my scenario: I have a feed with list of questions. In each question, I have a upvote button for upvoting this question.
So I will design an upvote button component sharing between other question components. When clicking to this button, button will trigger an event to server. method signature sometime such as:
func upvote(questionOwnerId, upvoteUserId) { ... }
After upvoting, upvote will dispatch an event for redux handle and update state respectively. So upvote button will always display latest state. (how many upvoted users for that question).
This is my problem: I don't know how to make sharing component (upvote component), after calling method to server then trigger unique redux path on redux tree.
I have a solution for this: Upvote component will receive following parameters:
total number of upvote.
question's user id.
redux path.
Then upvote function and Reducer will use redux path for update state on redux tree respectively. Does this method works well and look clean for project ? Or is there any "true" way for my problem?
#Edit: Redux path for example: feeds.item.questionList.question[0] for question component at 0 index. feeds.item.questionList.question[1] for question component at 1 index ... so Reducer can understand how to update redux tree.
Such shared component can be done by just receiving the proper props and passing a generic onClick events.
For example, let say we create component named <Question /> and it will the props:
votes - to display current number of votes.
onUpvote - as a click event for the up-vote button.
onDownvote - as a click event for the down-vote button.
id - it needs the id in order to pass it to the parent's
function.
question - The value of the question to display.
Now, your parent component will take a list of questions from the redux-store and will .map on it and will return for each question a <Question /> component with the respective props (id, votes and question).
As for the onUpVote and onDownVote you will pass functions that created in the parent. These functions will dispatch actions and that will handled by your reducer which will return the new state, this will trigger a re-render with new data to show.
I've created a simple example, note that i can't use redux here so i managed the state inside the App component, but i mentioned in comments where you can dispatch actions and what logic should go inside the reducers.
const questionsList = [
{
id: 1,
votes: 2,
question: "whats up"
},
{
id: 2,
votes: -1,
question: "whats the time"
},
{
id: 3,
votes: 0,
question: "where are you"
},
{
id: 4,
votes: 7,
question: "who are you"
}
];
class Question extends React.Component {
constructor(props) {
super(props);
this.onUpvote = this.onUpvote.bind(this);
this.onDownvote = this.onDownvote.bind(this);
}
onUpvote() {
const { id, onUpvote } = this.props;
onUpvote(id);
}
onDownvote() {
const { id, onDownvote } = this.props;
onDownvote(id);
}
render() {
const { votes, question } = this.props;
const voteClassName = `votes ${votes < 0 ? 'low' : 'high'}`;
return (
<div className="question-wrapper">
<div className="buttons-wrapper">
<button className="button" onClick={this.onUpvote}>+</button>
<div className={voteClassName}>{votes}</div>
<button className="button" onClick={this.onDownvote}>-</button>
</div>
<div className="question">{question}</div>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
questions: questionsList
};
this.onUpvote = this.onUpvote.bind(this);
this.onDownvote = this.onDownvote.bind(this);
}
onUpvote(id) {
const { questions } = this.state;
// you can dispatch an action here
// and instead of doing this logic in here you can do it in your reducer
const nextState = questions.map(question => {
if (question.id != id) {
return question;
}
return {
...question,
votes: question.votes + 1
};
});
this.setState({ questions: nextState });
}
onDownvote(id) {
const { questions } = this.state;
// you can dispatch an action here
// and instead of doing this logic in here you can do it in your reducer
const nextState = questions.map(question => {
if (question.id != id) {
return question;
}
return {
...question,
votes: question.votes - 1
};
});
this.setState({ questions: nextState });
}
render() {
const { questions } = this.state; // get the questions via props (redux store)
return (
<div>
{questions.map(q => (
<Question
id={q.id}
question={q.question}
votes={q.votes}
onUpvote={this.onUpvote}
onDownvote={this.onDownvote}
/>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
.question-wrapper{
display: flex;
flex-direction: row;
width: 150px;
box-shadow: 0 0 2px 1px #333;
margin: 10px 0;
padding: 5px 20px;
}
.buttons-wrapper{
display:flex;
flex-direction: column;
}
.button{
margin: 10px 0;
cursor: pointer;
}
.question{
align-self: center;
margin: 0 20px;
font-size: 22px;
}
.high{
color: #3cba54;
}
.low{
color: #db3236;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Resources