Iterating over children in stateless components react/react-native - reactjs

I was working on a react-native application and I created a common component for display list items.
<View style={styles.container}>
<ItemsWithSeparator style={styles.itemsContainer}>
<AppRow />
<AppRow />
</ItemsWithSeparator>
</View>
Now, my ItemListSeparator is just iterates over the children and renders the list, so I thought I would make this a stateless component.
const ItemsWithSeparator = function ({children,style}) {
const childrenList = [];
const length = React.Children.count(children);
React.Children.forEach(
children,
(child,ii) => {
childrenList.push(child);
if (ii !== length -1) {
childrenList.push(
<View
key={`separator-${ii}`}
style={[styles.separator]}
/>
);
}
}
);
return (
<View style={style}>
{children}
</View>
);
};
But this throws an error saying 'React' not found.
However, it works fine with class based components. Following is the code which is working fine.
class ItemsWithSeparator extends React.Component {
render () {
const {children,style} = this.props;
const childrenList = [];
const length = React.Children.count(children);
React.Children.forEach(
children,
(child,ii) => {
childrenList.push(child);
if (ii !== length -1) {
childrenList.push(
<View
key={`separator-${ii}`}
style={[styles.separator]}
/>
);
}
}
);
return (
<View style={style}>
{children}
</View>
);
}
}
Can anyone help me understanding this? TIA!!
Update:
I was just trying few something and apparently got his to work:-
const ItemsWithSeparator = function ({children,style,...props}) {
const childrenList = [];
const length = React.Children.count(children);
React.Children.forEach(
children,
(child,ii) => {
childrenList.push(child);
if (ii !== length -1) {
childrenList.push(
<View
key={`separator-${ii}`}
style={[styles.separator]}
{...props}
/>
);
}
}
);
return (
<View style={style}>
{children}
</View>
);
};
But I am still a bit confused on how is this working. If someone could explain I would really be great.

Here is refactored version so you don't have to do this weird React.Children stuff :D Notice that you can return array when mapping children. There you can make if statements if needed.
const ItemsWithSeparator = ({children, style, ...props}) => {
const finalFields = children.map((child, index) => {
return [
child,
index !== children.length - 1 && (
<View key={index} {...props} style={styles.separator} />
)
];
});
return (
<View style={style}>
{finalFields}
</View>
);
};

Related

React Native pass a function as props to child component

I am trying to pass a function from one component to its child, in this case Posts.js maps through each post and adds a prop called changeState. But It does not appear to be working.
The code for Posts.js
import Post from "./post"
export default function posts() {
const posts = [<arrayOfPosts>];
const [favoritesChanged, setFavoritesChanged] = useState(1);
const changeState = () => {
setFavoritesChanged(Math.random());
}
useEffect(() => {
console.log("favorites changed");
}, [favoritesChanged])
return (
{posts.map((post) => {
<Post changeState={changeState} key={post.id} />
}
)
}
Then in the post.js file we have:
const Post = ({ changeState }) => {
console.log("change state: ", changeState);
return (
<View>
<TouchableOpacity onPress={changeState}>
<Text>Click here to test.</Text>
</TouchableOpacity>
<Text>{post.title}</Text>
</View>
)
}
export default Post
But the press action doesn't fire the changeState function and where it is being console.logged it says undefined. Why is this not working?
You are missing returning the Post component JSX in the .map callback:
return (
{posts.map((post) => {
return <Post changeState={changeState} key={post.id} post={post} />
})}
);
or using an implicit arrow function return:
return (
{posts.map((post) => (
<Post changeState={changeState} key={post.id} post={post} />
))}
);
Ensure you are destructuring all the props you need that are passed:
const Post = ({ changeState, post }) => {
return (
<View>
<TouchableOpacity onPress={changeState}>
<Text>Click here to test.</Text>
</TouchableOpacity>
<Text>{post.title}</Text>
</View>
)
};
Try using this as the return in the posts component:
return (
<>
{
posts.map(val => <Post changeState={changeState} key={val}/>)
}
</>
)
See this as a reference : Sandbox reference

Passing state from function to component

My entire goal was to navigate from a screen while changing states in the screen I am navigating to. I have successfully done that in a minimal working example, however in my overall project, the screen I am navigating to needs to be passed the state through a couple levels.
I have two examples. In the first example(You must run the examples in IOS or android, you can see what I need to achieve, everything works as it should. You can move from screen3 to the home page and the states change along with the slider button moving.
In the second example, you can see right off the bat I have an error due to my attempt at passing states the same way I do in the original example however there is one more level I need to pass through in this example. You can see by removing line 39 in this demo, it removes the error so obviously I am not passing states correctly. I need to pass states from Home to Top3 to Slider
Here is example 1 and here is example 2 while I have also provided some code below that highlights the differences where the error occurs in the two examples.
Any insight at all is appreciated more than you know! Thank you.
Example1 -> you can see I directly render the slider button which causes zero issues.
const Home = ({ route }) => {
const [isVisile, setIsVisible] = React.useState(true);
const [whichComponentToShow, setComponentToShow] = React.useState("Screen1");
React.useEffect(() => {
if(route.params && route.params.componentToShow) {
setComponentToShow(route.params.componentToShow);
}
}, [route.params]);
const goToMap = () => {
setComponentToShow("Screen2");
}
const goToList = () => {
setComponentToShow("Screen1");
}
return(
<View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>
{whichComponentToShow === 'Screen1' && <ListHome />}
{whichComponentToShow === 'Screen2' && <MapHome />}
<View style={{position: 'absolute', top: 0, left: 0, right: 1}}>
<Slider
renderMap={goToMap}
renderList={goToList}
active={route.params && route.params.componentToShow==='Screen2'|| false}
/>
</View>
</View>
);
}`
Example2 -> You can see I render Slider in a file called Top3, I am struggling to pass these states from Home to Top3 to Slider.
const [isVisile, setIsVisible] = React.useState(true);
const [whichComponentToShow, setComponentToShow] = React.useState("Screen1");
React.useEffect(() => {
if(route.params && route.params.componentToShow) {
setComponentToShow(route.params.componentToShow);
goToMap()
}
}, [route.params]);
const goToMap = () => {
setComponentToShow("Screen2");
}
const goToList = () => {
setComponentToShow("Screen1");
}
return(
<View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>
{whichComponentToShow === 'Screen1' && <ListHome />}
{whichComponentToShow === 'Screen2' && <MapHome />}
<View style={{position: 'absolute', top: 0, left: 0, right: 1}}>
<Top3
renderMap={goToMap}
renderList={goToList}
active={route.params && route.params.componentToShow==='Screen2'|| false}
/>
</View>
</View>
);
}
Top3
export default class Top3 extends React.Component {
goToMap = () => {
this.props.renderMap();
};
goToList = () => {
this.props.renderList();
};
render() {
return (
<View>
<Slider renderMap={this.goToMap.bind(this)}
renderList={this.goToList.bind(this)}
active={active}/>
</View>
);
}
}
from your examples, I think you are not extracting active from props properly.
here is the demo working code your example2 code https://snack.expo.dev/4atEkpGVo
here is the sample code for component Top3
export default class Top3 extends React.Component {
goToMap = () => {
this.props.renderMap();
};
goToList = () => {
this.props.renderList();
};
render() {
const {active=false} = this.props;
return (
<View>
<Slider renderMap={this.goToMap.bind(this)}
renderList={this.goToList.bind(this)}
active={active}/>
</View>
);
}
}
if you want to share states between multiple screens, then you might want to use global stores like react context api or redux instead of passing states to each screen that would be simple

Dynamically map in React depending on the props received

I have a component that takes the props. If it's "1", it should use dataOne selector in order to use the right selector with filters. If it's "2" then use dataTwo and so on.
For example:
const [dataSet] = useState(route.params.dataSet);
const dataOne = useSelector(selectDataOne);
const dataTwo = useSelector(selectDataTwo);
const dataThree = useSelector(selectDataTwo);
const dataFour = useSelector(selectDataTwo);
The problem is that I want to map through one of these selectors depending on the prop and I want an elegant solution for it as dataSet[0].map while dataSet === "dataOne" will not work of course. What would be the alternative? What would be the prefer way to do so? Create a separate component with the switch statement? I want an elegant solution instead of spamming ternary operators like:
{dataSet == "1" && dataOne.map etc.}
{dataSet == "2" && dataTwo.map etc.}
What would be the best way to take the name from the props and map through it?
EDIT: For now I have this working solution, but not sure if it's the prettiest one:
const Data = (dataSet: string) => {
switch (dataSet) {
case "1":
return dataOne.map((c: any, i: number) => {
const card = c.dataSet === 1 && ;
if (i === dataOne.length - 1) {
return (
<View key={i} style={styles.lastMargin}>
<Card key={i} data={c} isOperating={c.isOperating} />
</View>
);
}
return card;
});
case "2":
return dataTwo.map((c: any, i: number) => {
const card = c.dataSet === 2 && <Card key={i} data={c} isOperating={c.isOperating} />;
if (i === dataTwo.length - 1) {
return (
<View key={i} style={styles.lastMargin}>
<Card key={i} data={c} isOperating={c.isOperating} />
</View>
);
}
return card;
});
case "3":
return dataThree.map((c: any, i: number) => {
const card = c.dataSet === 3 && <Card key={i} data={c} isOperating={c.isOperating} />;
if (i === dataThree.length - 1) {
return (
<View key={i} style={styles.lastMargin}>
<Card key={i} data={c} isOperating={c.isOperating} />
</View>
);
}
return card;
});
case "4":
return dataFour.map((c: any, i: number) => {
const card = c.dataSet === 4 && <Card key={i} data={c} isOperating={c.isOperating} />;
if (i === dataFour.length - 1) {
return (
<View key={i} style={styles.lastMargin}>
<Card key={i} data={c} isOperating={c.isOperating} />
</View>
);
}
return card;
});
}
};
You definitely shouldn't repeat your render logic. One way to do this could be by mapping each prop to a selector, getting the right one into a variable, and then using that in the render.
// map each prop to a selector
const selectorsMap = {
"1": dataOne,
"some-value": dataTwo,
...
};
// access the correct selector based on the prop
const data = selectorMap[dataSet];
return data.map(...);

Sending data from Child to Parent React

I have subdivided my components and I want to change state of text using deleteName function from child component. However I have used onPress={this.props.delete(i)} in my child component which is not working. The error that occurs for me is:
undefined variable "I"
Here is my code:
App.js
export default class App extends Component {
state = {
placeName: '',
text: [],
}
changeName = (value) => {
this.setState({
placeName: value
})
}
deleteName = (index) => {
this.setState(prevState => {
return {
text: prevState.text.filter((place, i) => {
return i!== index
})
}
}
}
addText = () => {
if (this.state.placeName.trim === "") {
return;
} else {
this.setState(prevState => {
return {
text: prevState.text.concat(prevState.placeName)
};
})
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<Input changeName={this.changeName}
value={this.state.placeName} />
<Button title="Send" style={styles.inputButton}
onPress={this.addText} />
</View>
<ListItems text={this.state.text} delete={this.deleteName}/>
{/* <View style={styles.listContainer}>{Display}</View> */}
</View>
);
}
}
and child component ListItems.js
const ListItems = (props) => (
<View style={styles.listitems}>
<Text>{this.props.text.map((placeOutput, i) => {
return (
<TouchableWithoutFeedback
key={i}
onPress={this.props.delete(i)}>
onPress={this.props.delete}
<ListItems placeName={placeOutput}/>
</TouchableWithoutFeedback>
)
})}
</Text>
</View>
);
You need to bind the index value at the point of passing the props to the child.
delete = index => ev => {
// Delete logic here
}
And in the render function, you can pass it as
items.map((item, index) => {
<ChildComponent key={index} delete={this.delete(index)} />
})
In your child component, you can use this prop as
<button onClick={this.props.delete}>Click me</button>
I have created a Sandbox link for your reference
Instead of onPress={this.props.delete(i)}, use onPress={() => this.props.delete(i)}
In order to have the cleaner code, you can use a renderContent and map with }, this);like below. Also you need to use: ()=>this.props.delete(i) instead of this.props.delete(i) for your onPress.
renderContent=(that)=>{
return props.text.map((placeOutput ,i) => {
return (
<TouchableWithoutFeedback key={i} onPress={()=>this.props.delete(i)}>
onPress={this.props.delete}
</TouchableWithoutFeedback>
);
}, this);
}
}
Then inside your render in JSX use the following code to call it:
{this.renderContent(this)}
Done! I hope I could help :)

react navigation custom tabBarComponent?

the navigationOptions code like that.
static navigationOptions = ({navigation})=>({
tabBarLabel:'查看',
headerTitle:navigation.state.params.title,
tabBarIcon: ({ tintColor,focused }) => (
<Image style={SKIN.tabImage} source={focused?AppImages.MyPost.lookchoose:AppImages.MyPost.look}/>
),
});
this is my Tab componet,how I can get tabBarLabel and tabBarIcon?
export default class Tab extends Component {
renderItem = (route, index) => {
const {
navigation,
jumpToIndex,
} = this.props;
const focused = index === navigation.state.index;
const color = focused ? this.props.activeTintColor : this.props.inactiveTintColor;
return (
<TouchableOpacity
key={index}
style={styles.tabItem}
onPress={() => jumpToIndex(index)}
>
<View
style={styles.tabItem}>
{this.props.renderIcon(color,focused)}
<Text style={{ color }}>{this.props.getLabel()}</Text>
</View>
</TouchableOpacity>
);
};
render(){
console.log('Tab this.props',this.props);
const {navigation,} = this.props;
const {routes,} = navigation.state;
return (
<View style={styles.tab}>
{routes && routes.map(this.renderItem)}
</View>
);
}
}
I custom Tab,now I want use that but some bug show me.
like that,
imagebug
please help me...
try updating the render method with this code:
render(){
console.log('Tab this.props',this.props);
const {navigation,} = this.props;
const {routes,} = navigation.state;
return (
<View style={styles.tab}>
//pass down the route and the index to the renderItem function
{routes && routes.map((route,index) => this.renderItem(route, index) )}
</View>
);
renderItem = (route, index) => {
const {
navigation,
jumpToIndex,
} = this.props;
const focused = index === navigation.state.index;
const color = focused ? this.props.activeTintColor : this.props.inactiveTintColor;
let TabScene = {
focused:focused,
route:route,
tintColor:color
};
return (
<TouchableOpacity
key={route.key}
style={styles.tabItem}
onPress={() => jumpToIndex(index)}
>
<View
style={styles.tabItem}>
{this.props.renderIcon(TabScene)}
<Text style={{ color }}>{this.props.getLabel(TabScene)}</Text>
</View>
</TouchableOpacity>
);
};

Resources