Hide Font Awesome icon component and display another based on state - javascript

I'm building a pomodoro timer with 4 sessions. When a 25-minute timer is up, 1 is added to a state variable sessionNumber.
I have four of these circle/unchecked checkboxes displayed when the pomodoro cycle starts:
<FontAwesomeIcon
icon={faCircle}
size="2x"
className="pomodoro-unchecked session-checkbox"
/>
Each time 1 is added to sessionNumber state, I would like to hide one and display a different icon component:
<FontAwesomeIcon
icon={faCheckCircle}
size="2x"
className="pomodoro-checked session-checkbox"
/>
The only ways I could think of doing this would take a whole lot of code -- for example if statements based on each session number, like with an if statement, if the session is 0, display 4 unchecked circles (with the code for all four components), and if the session is 1, display 1 checked circle and 3 unchecked circles, and so forth. The second way I considered would be to give each one a different class name and in the method that changes the session number, display and hide each one, based on which session number it is (that would be more complicated). Is there a simpler, more succinct method?

You could use an array in state. You could initialise the array with four "faCircle" and then use the array.fill() method on setState to fill up the icons with "faCheckCircle". Then you can map over the array to render the appropriate icon.
class SessionIcons extends React.Component {
constructor(props) {
super(props);
this.state = {
sessions: 0,
icons: ["faCircle", "faCircle", "faCircle", "faCircle"]
};
}
onAddSession = () => {
this.setState(state => ({
sessions: state.sessions + 1,
icons: state.icons.fill("faCheckCircle", 0, state.sessions + 1)
}));
};
render() {
return (
<div>
{this.state.icons.map((icon, index) => (
<FontAwesomeIcon
key={icon + index}
icon={icon === "faCircle" ? faCircle : faCheckCircle}
size="2x"
/>
))}
<button onClick={this.onAddSession}>Add session</button>
</div>
);
}
}
Demo: https://codesandbox.io/s/shy-tdd-qzs1n

class Timer extends React.Component{
state = { sessionNumber: 1}
checkTimer = () =>{
..your logic to check timer every 25 mins
this.setState({timerState:1})
}
render(){
Let font;
if( this.state.sessionNumber == 1)
{
font = <FontAwesomeIcon
icon={faCircle}
size="2x"
className="pomodoro-unchecked session-checkbox"
/>
}
else if(this.state.sessionNumber == 2)
{
font = FontAwesomeIcon
icon={faCheckCircle}
size="2x"
className="pomodoro-checked session-checkbox"
/>
return(
{font}
)
}
}

Related

Select Next/Previous list item in React without re-rendering

I'm learning React. Say that I have a ListContainer which renders several ListItems. I want to keep track of the currently selected ListItem, render it in another color, and be able to navigate up and down.
One way would be to store selectedItem as state in ListContainer, and send it down as a prop to ListItem. But if I do it this way, then every time I change selectedItem I will rerender all ListItems because they are dependent on selectedItem. (I should only have to re-render two ListItems, the one that gets deselected, and the one that gets selected).
Is there a way to implement next and previous function without re-rendering all items?
Note: I know that React doesn't re-render unnecessarily in the DOM, but I'm trying to optimize operations on virtual DOM also.
Edit: Here is my example in code. It renders a list, and when the user click one item it gets selected. We also see that "ListItem update" gets printed 100 times, each time we change selection, which happens regardless of PureComponent or React.memo.
let mylist = []
for (let i = 0; i < 100; i++) {
mylist.push({ text: "node:" + i, id: i })
}
window.mylist = mylist
const ListItem = React.memo (class extends Component {
componentDidUpdate() {
console.log('ListItem update')
}
render() {
let backgroundColor = this.props.item.id === this.props.selectedItem ? 'lightgreen' : 'white'
return (
<li
style={{ backgroundColor }}
onMouseDown={() => this.props.setSelected(this.props.item.id)}
>
{this.props.item.text}
</li>
)
}
})
class ListContainer extends Component {
constructor(props) {
super(props)
this.state = {
selectedItem: 10
}
this.setSelected = this.setSelected.bind(this)
}
setSelected(id) {
this.setState({ selectedItem: id })
this.forceUpdate()
}
render() {
return (
<ul>
{this.props.list.map(item =>
<ListItem
item={item}
key={item.id}
selectedItem={this.state.selectedItem}
setSelected={this.setSelected}
/>)}
</ul>
)
}
}
function App() {
return (
<ListContainer list={mylist} />
);
}
The state you suggesting is the right way to implement it...
The other problem with unnecessary renders of the list item can easily be soved by wrapping the export statement like this:
export default React.memo(ListItem)
This way the only elements that has changed their props will rerender.. be aware that overuse of This can cause memory leaks when using it unnecessarily...
UPDATE
according to your example in addition to the React.memo you can update the way you transfer props to avoid senfing the selected item in each item...
istead of:
let backgroundColor = this.props.item.id === this.props.selectedItem ? 'lightgreen' : 'white'
...
<ListItem
item={item}
key={item.id}
selectedItem={this.state.selectedItem}
setSelected={this.setSelected}
/>)}
do :
let backgroundColor = this.props.selectedItem ? 'lightgreen' : 'white'
...
<ListItem
item={item}
key={item.id}
selectedItem={item.id === this.state.selectedItem}
setSelected={this.setSelected}
/>)}
this way the react memo will prevent rerenders when it is possible...

State Change Causing Sidebar Reload

I am building an online store. When you click the checkout button, a sidebar slides into view showing the list of items in your cart. Inside of the cart is its list of items. You can change the quantity by toggling the up/down arrows in a Form.Control element provided by Bootstrap-React.
The way my code works is that when you toggle the up/down arrows to add or decrease the product quantity the state changes in the parent regarding what's in your cart. This triggers the child cart sidebar to close then reopen. I do not want this to happen! The sidebar should remain open.
I've tried two things; one is to use event.preventDefault() to try and make it so the page isn't refreshed, but this hasn't worked.
The other thing is trying to use shouldComponentUpdate and checking for whether the item quantity was changed, then preventing the app from re-rendering. This is the code I was using:
shouldComponentUpdate(nextProps, nextState) {
if (
nextState.cart &&
nextState.cart.length > 0 &&
this.state.cart.length > 0
) {
console.log("Next state cart num= " + nextState.cart[0].num)
console.log("curr state cart num= " + this.state.cart[0].num)
if (nextState.cart[0].num != this.state.cart[0].num) {
return false;
}
}
return true;
}
The problem is that my previous and future props are the same! Hence I can't write any code preventing re-rendering on item quantity change.
Can anyone provide some advice?
If your component is re rendering but its props and state aren't changing at all then you could prevent this with either React memo if you're using a function or if you're using a class based component then extending React.PureComponent instead of React.Component.
Both ways will do a shallow prop and state comparison and decide whether it should re render or not based on the result of said comparison. If your next props and state are the same as before then a re render will not be triggered.
Here's a codepen example so you can decide which one to use.
class App extends React.Component {
state = {
count: 0
};
handleClick = event => {
event.preventDefault();
this.setState(prevState => ({ count: prevState.count + 1 }));
};
render() {
return (
<div>
<span>Click counter (triggers re render): {this.state.count}</span>
<button style={{ marginLeft: "10px" }} onClick={this.handleClick}>
Click me to re render!
</button>
<SingleRenderClassComponent />
<SingleRenderFunctionComponent />
<AlwaysReRenderedClassComponent />
<AlwaysReRenderedFunctionComponent />
</div>
);
}
}
class SingleRenderClassComponent extends React.PureComponent {
render() {
console.log("Rendered React.PureComponent");
return <div>I'm a pure component!</div>;
}
}
const SingleRenderFunctionComponent = React.memo(
function SingleRenderFunctionComponent() {
console.log("Rendered React.memo");
return <div>I'm a memoized function!</div>;
}
);
class AlwaysReRenderedClassComponent extends React.Component {
render() {
console.log("Rendered React.Component");
return <div>I'm a class!</div>;
}
}
function AlwaysReRenderedFunctionComponent() {
console.log("Rendered function component");
return <div>I'm a function!</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));

Disable buttons from parent

I am creating a Quiz app for the sake of learning React Native.
I want that when a user presses an answer, all buttons should be disabled. I have no idea how to do this, I have tried all different approaches, like changing props of the buttons from the parent, setting state from the parent etc. I just can't figure it out. I can make the clicked button disabled, but that doesn't help since the other buttons are still clickable.
Parent
class Container extends Component {
state = { currentQuestion: questions[0] }
buttons = new Array();
componentWillMount() {
this.makeButtons();
}
makeButtons() {
for (let i = 0; i < 4; i++) {
const isCorrect = (i === 0); //the first answer is correct, this is how I keep track
const btn = (
<Button
key={i}
title={this.state.currentQuestion[i]}
isCorrect={isCorrect}
/>
);
this.buttons.push(btn);
}
shuffle(this.buttons);
}
render() {
return (
<View style={containerStyle}>
<Text style={textStyle}>
{this.state.currentQuestion.title}
</Text>
{this.buttons}
</View>
);
}
}
Button
class Button extends Component {
state = { color: "rgb(0,208,196)" };
handleEvent() {
const newColor = (this.props.isCorrect) ? "green" : "red";
this.setState({ color: newColor });
this.props.onPress();
}
renderButton() {
return (
<TouchableOpacity
style={buttonStyle}
onPress={this.handleEvent.bind(this)}
disabled={this.props.disabled}
>
<Text style={textStyle}>
{this.props.title}
</Text>
</TouchableOpacity>
);
}
render() {
return this.renderButton();
}
}
You are creating your button components within an instance variable once when the parent component loads, but never re-rendering them. This is an anti-pattern of React. Ideally, your components should all be rendered within render(), and their props should be computed from state, so you only need to worry about updating the state correctly and all your components render properly.
In this case, you should construct the data for your buttons at component load, save your button data within state, and render your buttons within render(). Add a "disabled" state to your Button component, and when a user presses one of the buttons, use a callback to set "disabled" state in the parent component, and all your buttons will re-render to be properly disabled.

react.js deleting one of few rendered components

Here is my first post.
I am in processs of creating todo app.
My app is adding new task to task list when plus button is clicked , and after few clicks u got few task simple , but the problem is that each task got delete Icon , which unfortunately by my lack of sufficient skills is deleting all components instead of the one , which icon belongs to.
Here is App.js code
class App extends React.Component {
constructor(props){
super(props);
this.handleDelete = this.handleDelete.bind(this);
this.addTask = this.addTask.bind(this);
this.state = {taskNum: 0,
delete: false
}
}
addTask(){
this.setState({
taskNum: this.state.taskNum +1,
delete:false
});
}
handleDelete(e){
console.log(e.target);
this.setState({delete: true});
}
render() {
const tasks = [];
for (let i = 0; i < this.state.taskNum; i += 1) {
tasks.push(!this.state.delete && <Task key={i} number={i} deleteTask={this.handleDelete}/>);
};
return (
<div className="ui container content">
<h2 className="centerHeader header">TODO LIST</h2>
<h3 className="taskheader secondaryHeader">Tasks <Icon className="addNew plus" action={this.addTask}/></h3>
<div className="ui container five column grid taskList">
{tasks}
</div> ...
and here is Task.js
export class Task extends React.Component {
constructor(props){
super(props);
this.dataChanged = this.dataChanged.bind(this);
this.state ={message: 'TASK' + (this.props.number+1),
}
}
customValidateText(text) {
return (text.length > 0 && text.length < 31);
}
dataChanged(data) {
console.log(data.message);
this.setState({message: data.message});
}
render(){
const centerRow = classNames('textCenter', 'row');
return (<div className="ui column task">
<div className={centerRow}><InlineEdit
validate={this.customValidateText}
activeClassName="editing"
text={this.state.message}
paramName="message"
change={this.dataChanged}
style={{
background: 'inherit',
textAlign:'center',
maxWidth: '100%' ,
display: 'inline-block',
margin: 0,
padding: 0,
fontSize: '1em',
outline: 0,
border: 0
}}
/></div>
<div className={centerRow}><Icon className="browser outline huge center"/> </div>
<div className={centerRow}><Icon className="large maximize"/><Icon className="large save saveTask"/><Icon className="large trash outline" action={this.props.deleteTask} /></div>
</div>
);
I thought of trying to e.target and select the parentNode but i am not sure if thats the proper solution since using react , so could u help me find efficient solution for this problem so that when trash icon is clicked it will delete only parent component.
One of the main reasons why react is powerful is that it give you the ability to maintain your DOM based on you data without having to do any manipulation to the DOM by yourself
So for your example to be more React JS friendly you need to do some changes, that will also fix your problem
1- You need to keep an actual state of your data, so adding a todo item means an actual real data added to your program, not just a component representation.
2- Removing a task represented by a component means removing the data it self, so deleting one of the tasks means deleting its actual data, and then react will handle updating the DOM for you, so the idea of a flag to hide a component is not React JS way
3- The way react knows when to render and how to handle all your data is managed by the component state .. so you save your data in component state and you only need to care about updating the state, then react will know that it will need to render again but now with the new updated list of tasks
I did some changes in your code with commented lines explaining why
class App extends React.Component {
constructor(props){
super(props);
this.handleDelete = this.handleDelete.bind(this);
this.addTask = this.addTask.bind(this);
this.state = {
tasks: [ ], // this is the array that will hold the actual data and based on its content react will handle rendering the correct data
counter : 1 // this counter is incremented every task addition just to make sure we are adding different task name just for the example explanation
}
}
}
addTask(){
this.setState({
tasks: this.state.tasks.push( "TASK" + counter); //This how we add a new task as i said you are adding an actual task data to the state
counter : this.state.counter + 1 //increment counter to have different task name for the next addition
});
}
//i changed this function to accept the task name so when you click delete it will call this function with task name as parameter
//then we use this task name to actually remove it from the tasks list data in our state
handleDelete(taskToDelete){
this.setState({
//the filter function below will remove the task from the array in our state
//After this state update, react will render the component again but now with the tasks list after removing deleting this one
tasks : this.state.tasks.filter((task) => {
if(task != taskToDelete)
return word;
})
});
}
render() {
const tasks = [];
//Notice here we pass an actual data to every Task component so i am adding prop message to take the value from this.state.tasks[index]
for (let i=0 ; i< this.state.tasks.length ; i++)
{
tasks.push(<Task key={i} message={this.state.tasks[i]} deleteTask={this.handleDelete}/>);
}
return (
<div className="ui container content">
<h2 className="centerHeader header">TODO LIST</h2>
<h3 className="taskheader secondaryHeader">Tasks <Icon className="addNew plus" action={this.addTask}/></h3>
<div className="ui container five column grid taskList">
{tasks}
</div> ...
)
}
}
Task Component
export class Task extends React.Component {
constructor(props){
super(props);
this.dataChanged = this.dataChanged.bind(this);
this.removeCurrentTask = this.removeCurrentTask.bind(this);
//Here i am setting the state from the passed prop message
this.state ={
message: this.props.message
}
}
customValidateText(text) {
return (text.length > 0 && text.length < 31);
}
dataChanged(data) {
console.log(data.message);
this.setState({message: data.message});
}
removeCurrentTask (){
//calling the deleteTask function with the current task name.
this.props.deleteTask(this.state.message);
}
render(){
const centerRow = classNames('textCenter', 'row');
return (
<div className="ui column task">
<div className={centerRow}><InlineEdit
validate={this.customValidateText}
activeClassName="editing"
text={this.state.message}
paramName="message"
change={this.dataChanged}
style={{
background: 'inherit',
textAlign:'center',
maxWidth: '100%' ,
display: 'inline-block',
margin: 0,
padding: 0,
fontSize: '1em',
outline: 0,
border: 0
}}
/></div>
<div className={centerRow}><Icon className="browser outline huge center"/> </div>
//Notice the action handler here is changed to use removeCurrentTask defined in current component
//BTW i don't know how Icon is handling the action property ... but now you can simply use onClick and call removeCurrentTask
<div className={centerRow}><Icon className="large maximize"/><Icon className="large save saveTask"/><Icon className="large trash outline" action={this.removeCurrentTask} /></div>
</div>
);
}
}

Rendering a list of items in React with shared state

Original Question
I'm trying to render a list of items using React. The key is that the items share a common state, which can be controlled by each item.
For the sake of simplicity, let's say we have an array of strings. We have a List component that maps over the array, and generates the Item components. Each Item has a button that when clicked, it changes the state of all the items in the list (I've included a code snippet to convey what I'm trying to do).
I'm storing the state at the List component, and passing down its value to each Item child via props. The issue I'm encountering is that the button click (within Item) is not changing the UI state at all. I believe the issue has to do with the fact that items is not changing upon clicking the button (rightfully so), so React doesn't re-render the list (I would have expected some kind of UI update given the fact that the prop isEditing passed onto Item changes when the List state changes).
How can I have React handle this scenario?
Note: there seems to be a script error when clicking the Edit button in the code snippet, but I don't run into it when I run it locally. Instead, no errors are thrown, but nothing in the UI gets updated either. When I debug it, I can see that the state change in List is not propagated to its children.
Edited Question
Given the original question was not clear enough, I'm rephrasing it below.
Goal
I want to render a list of items in React. Each item should show a word, and an Edit button. The user should only be able edit one item at a time.
Acceptance Criteria
Upon loading, the user sees a list of words with an Edit button next to each.
When clicking Edit for item 1, only item 1 becomes editable and the Edit button becomes a Save button. The rest of the items on the list should no longer show their corresponding Edit button.
Upon clicking Save for item 0, the new value is shown for that item. All the Edit buttons (for the rest of the items) should become visible again.
Problem
On my original implementation, I was storing an edit state in the parent component (List), but this state wasn't properly being propagated to its Item children.
NOTE: My original implementation is lacking on the state management logic, which I found out later was the main culprit (see my response below). It also has a bind bug as noted by #Zhang below. I'm leaving it here for future reference, although it's not really a good example.
Here's my original implementation:
const items = ['foo', 'bar'];
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
isEditing: false
};
}
toggleIsEditing() {
this.setState((prevState) => {
return {
isEditing: !prevState.isEditing
}
});
}
render() {
return (
<ul>
{items.map((val) => (
<Item value={val}
toggleIsEditing={this.toggleIsEditing}
isEditing={this.state.isEditing}/>
))}
</ul>
);
}
}
class Item extends React.Component {
render() {
return (
<li>
<div>
<span>{this.props.value}</span>
{ !this.props.isEditing &&
(<button onClick={this.props.toggleIsEditing}>
Edit
</button>)
}
{ this.props.isEditing &&
(<div>
<span>...Editing</span>
<button onClick={this.props.toggleIsEditing}>
Stop
</button>
</div>)
}
</div>
</li>
);
}
}
ReactDOM.render(<List />, document.getElementById('app'));
<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>
<body>
<div id="app" />
</body>
you didn't bind the parent scope when passing toggleIsEditing to child component
<Item value={val}
toggleIsEditing={this.toggleIsEditing.bind(this)}
isEditing={this.state.isEditing}/>
I figured out the solution when I rephrased my question, by rethinking through my implementation. I had a few issues with my original implementation:
The this in the non-lifecycle methods in the List class were not bound to the class scope (as noted by #ZhangBruce in his answer).
The state management logic in List was lacking other properties to be able to handle the use case.
Also, I believe adding state to the Item component itself was important to properly propagate the updates. Specifically, adding state.val was key (from what I understand). There may be other ways (possibly simpler), in which case I'd be curious to know, but in the meantime here's my solution:
const items = ['foo', 'bar'];
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
editingFieldIndex: -1
};
}
setEdit = (index = -1) => {
this.setState({
editingFieldIndex: index
});
}
render() {
return (
<ul>
{items.map((val, index) => (
<Item val={val}
index={index}
setEdit={this.setEdit}
editingFieldIndex={this.state.editingFieldIndex} />
))}
</ul>
);
}
}
class Item extends React.Component {
constructor(props) {
super(props);
this.state = {
val: props.val
};
}
save = (evt) => {
this.setState({
val: evt.target.value
});
}
render() {
const { index, setEdit, editingFieldIndex } = this.props;
const { val } = this.state;
const shouldShowEditableValue = editingFieldIndex === index;
const shouldShowSaveAction = editingFieldIndex === index;
const shouldHideActions =
editingFieldIndex !== -1 && editingFieldIndex !== index;
const editableValue = (
<input value={val} onChange={(evt) => this.save(evt)}/>
)
const readOnlyValue = (
<span>{val}</span>
)
const editAction = (
<button onClick={() => setEdit(index)}>
Edit
</button>
)
const saveAction = (
<button onClick={() => setEdit()}>
Save
</button>
)
return (
<li>
<div>
{ console.log(`index=${index}`) }
{ console.log(`editingFieldIndex=${editingFieldIndex}`) }
{ console.log(`shouldHideActions=${shouldHideActions}`) }
{
shouldShowEditableValue
? editableValue
: readOnlyValue
}
{
!shouldHideActions
? shouldShowSaveAction
? saveAction
: editAction
: ""
}
</div>
</li>
);
}
}
ReactDOM.render(<List />, document.getElementById('app'));
<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>
<body>
<div id="app" />
</body>

Categories

Resources