React: Change Styling on User Action

There are a few common ways to change the styling of a given React Component from common user actions such as clicking. The change in the style is normally a result of the change in the component state. What we can do is to set the styling based on the state.

Supplying a overwriting Style or CSS to the component (inline)

Pass the React Style or CSS props into the component which performs simple checks on the state in the same component.

<ul>
{todos.map(todo=><li key={todo.id}
onClick={()=>{todoStore.dispatch({
type:'TOGGLE_TODO',
id: todo.id
});}}
style={{textDecoration: todo.completed?'line-through': 'none'}}>
{todo.text}
</li>)}
</ul>
</ul>

Spit the styling out to a different component (Check in a sub component)

If the conditions to check for the style change is more complex, another option is to split the check to a separate component. Instead of passing in the Styles and the {todo.text} to the <li> directly, we pass the {todo} state to a separate <TodoItem> component.

<ul>
{todos.map(todo=><li key={todo.id}
onClick={()=>{todoStore.dispatch({
type:'TOGGLE_TODO',
id: todo.id
});}}
<TodoItem todo={todo}/></li>)}
</ul>

Inside the <TodoItem/>, we can perform the logics of checking for the state separately and return different styled element based on the state.

const TodoItem = ({todo}) => {
if (todo.completed){
return <strike>{todo.text}</strike>;
}
return <span>{todo.text}</span>;
};
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.