reactjs - Create Toggle For Dynamically Created Buttons - javascript

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.

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...

React createRef for a childComponent inside a ViewPager in React Native

I have created a signup module with three steps in my react native application where I have put all of the fields in the state of the parent component, and that gave me a very overloaded JSX file, So I am trying to move all of the fields validation functions to the related step and catch the returned value 'valid/ not valid' in the parent screen so I can move to the next step by clicking on the next button which will navigate to the next viewpager page.
So I have tried to use the React.createRef to reference the child step in the parent and call the methods within the child in the future:
SignupScreen.jsx (Parent):
constructor(props) {
super(props);
this.state = {
...fields,
}
this.signupStepOneRef = React.createRef();
}
render(){
return (
<ViewPager
initialPage={0}
style={styles.fieldsContainer}
scrollEnabled={false}
ref={(vp) => (this.viewPager = vp)}
>
<SignupStepOne
fieldsContainerStyle={styles.fieldsContainer}
scrollViewStyle={styles.scrollView}
key="1"
onInputChanged={this.handleChange}
stepOneErrors={this.state.stepOneErrors}
ref={this.signupStepOneRef}
/>
...OtherSteps
</ViewPage>
)
}
But this code gives me an Object : {current: null} when I console.log(this.signupStepOneRef).
The official documentation says that this won't work if the child is a function, but changing it to a class component didn't help either.
I have also tried the:
ref={(obj) => this.signupStepOneRef = obj}
syntax but also gives me the same null current object.
I finally found a solution, since viewpager children cannot be referenced directly I have wrapped up the child page in a View component and that solved my issue.
The solution code:
<ViewPager
initialPage={0}
style={styles.fieldsContainer}
scrollEnabled={false}
ref={(vp) => (this.viewPager = vp)}
>
<View key="1">
<SignupStepOne
fieldsContainerStyle={styles.fieldsContainer}
scrollViewStyle={styles.scrollView}
onInputChanged={this.handleChange}
stepOneErrors={this.state.stepOneErrors}
ref={this.signupStepOneRef}
/>
</View>
...OtherSteps
</ViewPage>
The key attribute needs to be moved to the wrapper view.

React Native not rendering on prop change

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>
}
}

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.

ReactJS keeping a single "Active" state between multiple components

I am attempting to keep with best practices, while adhering to the documentation. Without creating to many one-off methods to handle things for a maintainability standpoint.
Anyway all in all, I am trying to achieve a state between sibling elements that is in sorts an "active" state visually at the least. With something like jQuery I would simply do..
$(document).on('.nav-component', 'click', function(e) {
$('.nav-component').removeClass('active');
$(this).addClass('active');
});
However in react, each component in it of itself is independent of the next and previous, and should remain as such per the documents.
That said, when I am handling a click event for a component I can successfully give it a state of active and inactive, toggling it on and off respectively. But I end up in a place where I have multiple "active" elements when I don't need them as such.
This is for setting up a navigation of sorts. So I want the one in use at the moment to have that active class while the rest won't
I use an app.store with reflux to set state for multiple pages/components. You can do the same passing state up to a common component but using the flux pattern is cleaner.
class AppCtrlRender extends Component {
render() {
let page = this.state.appState.currentPage;
let hideAbout = (page != 'about');
let hideHome = (page != 'home');
return (
<div id='AppCtrlSty' style={AppCtrlSty}>
<div id='allPageSty' style={allPageSty}>
<AboutPage hide={hideAbout} />
<HomePage hide={hideHome} />
</div>
</div>
);
}
}
let getState = function() { return {appState: AppStore.getAppState(),}; };
export default class AppCtrl extends AppCtrlRender {
constructor() {
super();
this.state = getState();
}
componentDidMount = () => { this.unsubscribe = AppStore.listen(this.storeDidChange); }
componentWillUnmount = () => { this.unsubscribe(); }
storeDidChange = () => { this.setState(getState()); }
}
In the page/component check for this.props.hide.
export default class AboutPage extends Component {
render() {
if (this.props.hide) return null;
return (
<div style={AboutPageSty}>
React 1.4 ReFlux used for app state. This is the About Page.
<NavMenu />
</div>
);
}
}
Siblings needing to share some sort of state in React is usually a clue that you need to pull state further up the component hierarchy and have a common parent manage it (or pull it out into a state management solution such as Redux).
For sibling components where only one can be active at a time, the key piece of state you need is something which lets you identify which one is currently active and either:
pass that state to each component as a prop (so the component itself can check if it's currently active - e.g. if each item has an associated id, store the id of the currently active one in a parent component and pass it to each of them as an activeId prop)
e.g.:
var Nav1 = React.createClass({
getInitialState() {
return {activeId: null}
},
handleChange(activeId) {
this.setState({activeId})
},
render() {
return <div className="Nav">
{this.props.items.map(item =>
<NavItem
activeId={this.state.activeId}
item={item}
onClick={this.handleChange}
/>
)}
</div>
}
})
or use it to derive a new prop which is passed to each component (such as an active prop to tell each component whether or not it's currently active - e.g. in the id example above, check the id of each component while rendering it: active={activeId === someObj.id})
e.g.:
var Nav2 = React.createClass({
// ... rest as per Nav1...
render() {
return <div className="Nav">
{this.props.items.map(item =>
<NavItem
active={this.state.activeId === item.id}
item={item}
onClick={this.handleChange}
/>
)}
</div>
}
})
The trick with React is to think of your UI in terms of the state you need to render if from scratch (as if you were rendering on the server), instead of thinking in terms of individual DOM changes needed to make the UI reflect state changes (as in your jQuery example), as React handles making those individual DOM changes for you based on complete renderings from two different states.

Categories

Resources