Sending data from Child to Parent React - reactjs

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 :)

Related

How to refer to previous state in React's child component?

Let's say I have this component:
class MyForm {
render() {
return (
<>
<h3>Remember my Setting</h3>
<Toggle
value={this.state.rememberMe}
onClick={() => {
this.setState(prevState => ({ rememberMe: !prevState.rememberMe }));
}}
/>
</>
)
}
}
How can I pass this prevState if its wrapped in child component? Is this acceptable?
class MyForm {
render() {
return (
<PartialForm
onClick={(v) => {
this.setState({ rememberMe: v });
}}
/>
)
}
}
const PartialForm = (props) => {
return (
<>
<h3>Remember my Setting</h3>
<Toggle
value={props.rememberMe}
onClick={() => {
props.onClick(!props.rememberMe);
}}
/>
</>
);
}
I want to know if accessing props.rememberMe is the same and safe as accessing prevState.rememberMe in parent component. Thanks
In my opinion, the way you're doing is safe and it has no conflicts at all.
I can simply demonstrate those re-rendering steps here:
Pass the current state to PartialForm
Trigger toggle click props.onClick for updating rememberMe in the upper component
The upper component gets re-rendered, and then your child component will have the latest state of rememberMe
By the way, you also forget to pass rememberMe in <PartialForm />
class MyForm {
render() {
return (
<PartialForm
rememberMe={rememberMe}
onClick={(v) => {
this.setState({ rememberMe: v });
}}
/>
)
}
}
const PartialForm = (props) => {
return (
<>
<h3>Remember my Setting</h3>
<Toggle
value={props.rememberMe}
onClick={() => {
props.onClick(!props.rememberMe);
}}
/>
</>
);
}

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

React component not running componentDidmount in my project, so I get error isEdit of undefined?

When I run my react-native component, I get the following error:
However, in the debugger in constructor and componentWillmount and render lifecycle, isEdit is false.
Only componentDidmount is not printing anything, so I think the component is not running componentDidmount lifecycle and I don't know the error reason for this.
constructor(props: IProps) {
// isEdit: false
super(props);
// const {navigation} = this.props;
props.navigation.setOptions({
headerRight: () => {
return <HeaderRightBtn onSubmit={this.onSubmit} />;
},
});
}
componentWillmount() {
// isEdit: false
}
componentDidmount() {
// isEdit of undefined
}
render() {
// isEdit: false
const {categorys, isEdit} = this.props;
const {myCategorys} = this.state;
const classifyGroup = _.groupBy(categorys, (item) => item.classify);
return (
<ScrollView style={styles.container}>
<Text style={styles.classifyName}>我的分类</Text>
<View style={styles.classifyView}>
<DragSortableView
dataSource={myCategorys}
renderItem={this.renderItem}
sortable={isEdit}
fixedItems={fixedItems}
keyExtractor={(item) => item.id}
onDataChange={this.onDataChange}
parentWidth={parentWidth}
childrenWidth={itemWidth}
childrenHeight={itemHeight}
marginChildrenTop={margin}
onClickItem={this.onClick}
/>
{/* {myCategorys.map(this.renderItem)} */}
</View>
<View>
{Object.keys(classifyGroup).map((classify) => {
return (
<View key={classify}>
<Text style={styles.classifyName}>{classify}</Text>
<View style={styles.classifyView}>
{classifyGroup[classify].map((item, index) => {
if (
myCategorys.find(
(selectedItem) => selectedItem.id === item.id,
)
) {
return null;
}
return this.renderUnSelectedItem(item, index);
})}
</View>
</View>
);
})}
</View>
</ScrollView>
);
}
}
Correct names of methods are
“componentDidMount()” and “UNSAFE_componentWillMount()” as per componentdidmount and unsafe_componentwillmount respectively.
Note that componentWillMount() is changed to UNSAFE_componentWillMount() as per the official docs.

react native - undefined is not a function updateState()

I'm passing a function from Parent to Children components using FlatList but for some reason, the error occurs that undefined is not a function referring to updateState function.
Here's the parent component:
class Home extends Component {
/*
data items here
*/
updateState(data) {
this.setState({ data: data });
}
renderItem() {
return (
<ItemView updateParentState={ (data) => this.updateState(data) } />
)
}
render() {
return (
<FlatList
style={styles.fragmentContainer}
data={this.state.items}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItem} />
)
}
}
Here's the child view:
class ItemView extends Component {
constructor(props) {
super(props);
this.state = {
data: "some data"
};
}
render() {
return (
<TouchableOpacity onPress={ () => this.props.updateParentState(this.state.data) }>
<Text>Item name here</Text>
</TouchableOpacity>
)
}
}
This should fix your problem:
render() {
return (
<FlatList
style={styles.fragmentContainer}
data={this.state.items}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItem.bind(this)} />
)
}
You should always use the .bind(this) function if you're going to pass a function as props so that this does not get lost. Or you could use the arrow function if you're not a fan of .bind.
Ex:
{() => this.renderItem()}

Iterating over children in stateless components react/react-native

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

Resources