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.
Related
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...
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"));
I have created the following component:
type ToggleButtonProps = { title: string, selected: boolean }
export default class ToggleButton extends Component<ToggleButtonProps>{
render(){
return (
<TouchableWithoutFeedback {...this.props}>
<View style={[style.button, this.props.selected ? style.buttonSelected : style.buttonDeselected]}>
<Text style={[style.buttonText, this.props.selected ? style.buttonTextSelected : style.buttonTextDeselected]}>{this.props.title}</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
The styles are simple color definitions that would visually indicate whether a button is selected or not. From the parent component I call (item is my object):
item.props.selected = true;
I've put a breakpoint and I verify that it gets hit, item.props is indeed my item's props with a selected property, and it really changes from false to true.
However, nothing changes visually, neither do I get render() or componentDidUpdate called on the child.
What should I do to make the child render when its props change? (I am on React Native 0.59.3)
You can't update the child component by literally assigning to props like this:
item.props.selected = true;
However, there are many ways to re-render the child components. But I think the solution below would be the easiest one.
You want to have a container or smart component which will keep the states or data of each toggle buttons in one place. Because mostly likely, this component will potentially need to call an api to send or process that data.
If the number of toggle buttons is fixed you can simply have the state like so:
state = {
buttonOne: {
id: `buttonOneId`,
selected: false,
title: 'title1'
},
buttonTwo: {
id: `buttonTwoId`,
selected: false,
title: 'title2'
},
}
Then create a method in the parent which will be called by each child components action onPress:
onButtonPress = (buttonId) => {
this.setState({
[buttonId]: !this.state[buttonId].selected // toggles the value
}); // calls re-render of each child
}
pass the corresponding values to each child as their props in the render method:
render() {
return (
<View>
<ToggleButton onPressFromParent={this.onButtonPress} dataFromParent={this.state.buttonOne} />
<ToggleButton onPressFromParent={this.onButtonPress} dataFromParent={this.state.buttonTwo} />
...
finally each child can use the props:
...
<TouchableWithoutFeedback onPress={() => this.props.onPressFromParent(this.props.dataFromParent.id)}>
<View style={[style.button, this.props.dataFromParent.selected ? style.buttonSelected : style.buttonDeselected]}>
...
I left the title field intentionally for you to try and implement.
P.S: You should be able to follow the code as these are just JS or JSX.
I hope this helps :)
Because children do not rerender if the props of the parent change, but if its STATE changes :)
Update child to have attribute 'key' equal to "selected" (example based on reactjs tho')
Child {
render() {
return <div key={this.props.selected}></div>
}
}
Currently, I am facing a problem with JS/React/React-Native. I am pulling categories from an API, and I am making buttons out of the results (they change often based on different variables in the URL). The code I am using to do this is as follows:
const cats = singles.map((d) => {
return (
<TouchableOpacity key={d} style={styles.Settingcats}><Text style={{color: '#f55f44'}}>{d}</Text></TouchableOpacity>
)}
With the dynamically generated buttons I want them to be able to be toggled in the application. When I tried to utilize the states with the following code:
const cats = singles.map((d) => {
return (
<TouchableOpacity key={d} onPress={ _ => this.changeStyle} style={this.state.style === 0 ? styles.Settingcats : styles.SelSettingcats}><Text style={{color: '#f55f44'}}>{d}</Text></TouchableOpacity>
)}
And realized that, since this was referring to one state for all of the buttons, it would change all of the buttons styles. So I tried to think otuside the box a bit and thought of using the ID as a state name, creating the state, and utilizing the state through an external function to change it's value.
const cats = singles.map((d) => {
return (
<TouchableOpacity key={d} onPress={ _ => this.changeStyle(d)} style={this.state([d]) === 0 ? styles.Settingcats : styles.SelSettingcats}><Text style={{color: '#f55f44'}}>{d}</Text></TouchableOpacity>
)}
changeStyle(d){
this.setState({
[d] : 1
})}
Which throws an error because the state is being utilized as if it is a function.
What practices can I use to make dynamically created buttons have their own separate toggle events?
Other things I have tried: Custom Switches, material-UI but I get stuck at the same problem when it comes to having unique functions for the toggled buttons.
Instead of trying to manage a list of states at the top level, move TouchableOpacity into a component that handles the toggle state internally.
class MyButton extends React.Component {
constructor(props) {
super(props)
this.state = {
toggle: false
}
this.setToggle = this.setToggle.bind(this);
}
setToggle(){
this.setState({
toggle: !this.state.toggle
})
}
render(){
return <TouchableOpacity onClick={this.setToggle} className={this.state.toggle ? 'red' : 'blue'}>{this.props.name}</TouchableOpacity>
}
}
You can render a list of these and each one manages it own toggle state independent of the others.
Here is a fiddle example: https://jsfiddle.net/n5u2wwjg/220149/
The method that I used to achieve this, with many thanks from #simbathesailor
I utilized the variable in the state to dynamically create states that I could utilize in telling whether the buttons were "on" or "off" by using
this.state[d]
Where d was the dynamic variable that I created with my TouchableOpaque component.
So I have a list that was returned from an API request (not important)
lets call it list = [1,2,3,4,5,6,7];
Now, inside render(), I have something like the following
render(){
<Wrapper>
{list.map((i) => {
return (<Button id = {i} onClick = {this.customFunc.bind(this, i)} />)
}
</Wrapper>
}
Now, I have another list, lets call it list_check = [false...] (for all 7 elements listed above)
Assume that customFunc changes the respective button id in list_check from false to true.
e.g. if I clicked button 1 (id = 1) then list_check becomes [false, true, false...]
** Now my problem is: I have 2 styled components, Button and Button_Selected,
how can i dynamically change between the 2 styled components so that if that unique button is clicked (change list_check[index] = true), the element becomes Button_Selected instead of Button (The entire list is initalized as Button since all elements are false)
Just to make it clear:
Both arrays are located in this.state and by 2 styled components I mean there exists
const Button = styled.div`
//styling here
`;
and
const Button_Selected = Button.extend`
//Small styling change to differentiate between selected and not selected
`;
edit: all answers are great! too bad I can only select one :(
You could just save the component to another variable.
this.state.list_check.map((item, i) => {
const NecessaryButton = item ? SelectedButton : Button;
return <NecessaryButton onClick={() => this.makeSelected(i)}>Normal Button</NecessaryButton>
})
You can see a live example here.
Although you can return 2 buttons based on conditional rendering .You can also pass props to your styled Button so that based on props you can change your styles.
render(){
<Wrapper>
{list.map((i) => {
return (<Button id = {i} isSelected={this.state.list_check[i]} onClick = {this.customFunc.bind(this, i)} />)
}
</Wrapper>
}
And in your styled Button:
const Button = styled.div`
styleName: ${props => props.isSelected ? 'styling_if_Selected' : 'styling_if_not_selected'};
`;
The easiest approach would be to have a single Button component and handle in the state if it was selected. Depending on this state you could switch classes.
Example:
class Button extends React.Component {
state = {
isSelected: false
};
handleClick() {
//Here we will set the state change and call the onClick function passed by props
this.setState({isSelected: !this.state.isSelected}, () => { this.props.onClick(); });
}
render() {
return (
<button
class={this.state.isButtonSelected ? "classBtnSelected" : "classBtnDefault"}
onClick={this.handleClick}
/>
);
}
}
Still, if you want to switch components you can use state to control if it was selected and do a conditional rendering. Example:
render(){
<Wrapper>
{list.map((i) => {
return (this.state.isSelected
? <Button id={i} onClick = {this.customFunc.bind(this, i)} />
: <Button_Selected id={i} onClick = {this.customFunc.bind(this, i)} />)
}
</Wrapper>
}