I am confused about how to properly dynamically add/create same components on button press for react native. I have used .map(()=>{}) on existing info to create components and then display the results.
Would I have to save each new component into a setstate array, then map that?
I looked a little into refs, but wasn't sure how that was better than just a setstate. The problem I see is if I want to update the value for each component, how would I go about that if their all originally duplicates?
Something along the lines of this:
class SingleExercise extends Component {
constructor(props) {
super(props);
this.state = {
objInfo: this.props.navigation.getParam("obj"),
currentSetSelected: 0
};
this.addSet = this.addSet.bind(this);
}
addSet = () => {
return (
<addSet />
)
}
render() {
const { navigation } = this.props;
return (
<View style={{ flex: 1 }}>
<View style={{ height: 80 }}>
<addSet />
<View>
<Button //here
large={false}
onPress={() => {
this.addSet();
}}
title={"add more"}
/>
</View>
</View>
</View>
);
}
}
const addSet = () => {
return (
<TouchableHighlight>
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
defaultValue={'test'}
onChangeText={(text) => this.setState({text})}
/>
</View>
</TouchableHighlight>
);
}
Here is what I would do:
Every click on addSet button should increment the AddSets counter like this:
<Button
large={false}
onPress={() => {
this.setState({addSetsCounter: this.state.addSetsCounter});
}}
title={"add more"}
/>
After every state update your component will be re-rendered. So now, all you need to do is to forLoop in through that counter and return as many AddSets components as needed. A simple for loop with .push() inside would do.
Inside render, before return place something like that:
let sets =[];
for(let i =0;i<this.state.addSetsCounter;i++){
sets.push(<AddSets key="AddSets-{i}"/>);
}
Then simply render your {sets}.
I cannot fully test that right now, I wrote that from the top of my head, just play with the above, at least I hope it points you in a right direction.
Related
I have some references in a React Native Web application - these references work on React Native, but not RNW.
For example, I have this code:
this.highlight.current._children[i].setNativeProps({ style: { backgroundColor: "black" } });
this.highlight.current._children[i]._children[0]._children[0].setNativeProps({ style: { color: "white" } })
this.highlight.current._children[i]._children[1]._children[0].setNativeProps({ style: { color: "white" } })
Which is based on this:
this.highlight = React.createRef();
Which is passed into a child component as a prop and used as such:
<View ref={this.props.highlight}>
It has several children (who have nested children as well).
However, on the web, there is no ._children at all.
How do I access children?
It's possible to do DOM manipulation directly if Platform.OS === 'web':
let dom = ReactDOM.findDOMNode(this.highlight.current);
... DOM manipulations
But this feels messy and code-duplicating if not absolutely necessary. I'd much rather apply my modifications to the reference directly via the React Native API.
EDIT: More code - here's my structure and a few relevant functions to the problem. I cut out irrelevant parts to try to make the code I posted smaller
class DetailBody extends Component {
constructor() {
super();
}
render() {
return (
<ScrollView >
<Text>{this.props.article.intro}</Text>
<View ref={this.props.highlight}>
{this.props.article.json.results.map((content, index) => (
<View key={index} style={{}}>
{content.pinyin ? (
<Fragment>
<View>
<Text>
{content.pinyin}
</Text>
</View>
<View>
<Text>
{content.simplified}
</Text>
</View>
</Fragment>
) : (
<Fragment>
<View>
<Text>
</Text>
</View>
<View>
<Text>
{content.characters}
</Text>
</View>
</Fragment>
)
}
</View>
))}
</View>
</ScrollView>
)
}
}
class Detail extends Component {
constructor() {
super();
this.state = {
currentVal: 0,
};
this.traverseCharacters = this.traverseCharacters.bind(this)
this.highlight = React.createRef();
}
async traverseCharacters(i) {
this.highlight.current._children[i].setNativeProps({ style: { backgroundColor: "black" } });
this.highlight.current._children[i]._children[0]._children[0].setNativeProps({ style: { color: "white" } })
this.highlight.current._children[i]._children[1]._children[0].setNativeProps({ style: { color: "white" } })
if (i > 0) {
this.clearCharacters(i)
}
}
render() {
return (
<DetailBody {...this.props} article={this.state.article} highlight={this.highlight} />
);
}
}
[Edit]: Since this 'someone's work' is for class component, here is one of my answer using dynamic refs with a functional component : Dynamic refs with functional component. It uses a useRef() hooks to store your dynamic refs, and so they're accessible wherever you want, with a specific id.
After trying things for a moment now, I cannot find a clean way of doing what you want to do. However, there is solutions for this, as you said with the ReactDOM. Another thing that came in my mind would be to set your refs in your child and then pass it to the parent.
Here is someone doing 'dynamic' ref in a .map using the key attribute, maybe it can be of use to you : Someone's work
Now, using direct manipulation isn't a good practice, so using this isntead of ReactDOM.findDOMNode... I don't really know which is one is worse but both are messy i guess.
setNativeProps isn't available on the children element. You either need to provide a refs to the intended child elements yourself before calling setNativeProps on them
For a ref solution you could make use of ref callbacks like below and add a ref to each and every element that you wish to update dynamically
class DetailBody extends Component {
setRef = (i, j, ref) => {
if(this.highlight[i]) {
this.highlight[i][j] = ref;
} else {
this.highlight[i] = {[j]: ref};
}
}
render() {
return (
<ScrollView >
<Text>{this.props.article.intro}</Text>
<View>
{this.props.article.json.results.map((content, index) => (
<View key={index} style={{}} ref= {(ref) => this.setRef(index, 'root', ref)}>
{content.pinyin ? (
<Fragment>
<View ref= {(ref) => this.setRef(index, 0, ref)}>
<Text>
{content.pinyin}
</Text>
</View>
<View ref= {(ref) => this.setRef(index, 1, ref)}>
<Text>
{content.simplified}
</Text>
</View>
</Fragment>
) : (
<Fragment>
<View ref= {(ref) => this.setRef(index, 0, ref)}>
<Text>
</Text>
</View>
<View ref= {(ref) => this.setRef(index, 1, ref)}>
<Text>
{content.characters}
</Text>
</View>
</Fragment>
)
}
</View>
))}
</View>
</ScrollView>
)
}
}
class Detail extends Component {
constructor() {
super();
this.state = {
currentVal: 0,
};
this.traverseCharacters = this.traverseCharacters.bind(this)
this.highlight = {};
}
async traverseCharacters(i) {
this.highlight[i].root.setNativeProps({ style: { backgroundColor: "black" } });
this.highlight[i][0].setNativeProps({ style: { color: "white" } })
this.highlight[i][1].setNativeProps({ style: { color: "white" } })
}
render() {
return (
<DetailBody {...this.props} article={this.state.article} highlight={this.highlight} />
);
}
}
I am trying to render a FlatList inside a component. The Component itself is inside a ScrollView.
I am using map function to loop through the data to pass into the component.
Earlier I was using ScrollView instead of FlatList. It was working fine, but was rendering slow. So I decided to use FlatList.
Here's my code:
renderComp(){
const { filtersView,cats,cats_title, clearStyle} = styles;
const data = this.props.ingreds;
const arr = Object.entries(data);
return arr.map(i=> {
const name= i[0];
const items_obj = i[1];
const items = Object.values(items_obj);
return(
<View key={name} style= {filtersView}>
<View style={cats}>
<Text style ={cats_title}>{name}</Text>
<Text style={clearStyle}>Clear All</Text>
</View>
<View style={{justifyContent:'flex-start', alignItems:'flex-start'}}>
<FlatList
style={{ marginRight:6}}
data={items}
keyExtractor={(x,i)=> i.toString()}
renderItem={({item}) =>{
this.renderItems(item)
}}
/>
</View>
</View>
)
})
}
And here's the ScrollView Component:
<ScrollView contentContainerStyle={{alignItems:'flex-start',
justifyContent:'flex-start',flex:1, height:72}} >
{this.renderComp()}
</ScrollView>
And The loop stops after one iteration.
Here's the output: https://i.stack.imgur.com/yM151.png
Any suggestions?
ReactNative FlatList renderItem method should return a ?React.Element component. In your case either use return this.renderItems or skip the inner brackets.
https://facebook.github.io/react-native/docs/flatlist#renderitem
({item}) => this.renderItems(item)}
I'm developing in React Native.
I have a FlatList that renders items. I have added TouchableOpacity and would like to call a function upon press of that item, but the function is not being called.
When I click on the item I get an error of cannot find variable: _onPress
I think it's an issue with scoping. Would someone be able to explain to me what is going wrong please?
I guess a secondary question is: will my _onPress console.log the item name by passing the prop in like I have?
export default class ModalScreen extends React.Component {
//..
_onPress = (item) => {
console.log('Clicked:' + item)
};
renderItem({ item }) {
return (
<TouchableOpacity onPress={() => this._onPress(item)}>
<View>
<Text>{item.name}</Text>
</View>
</TouchableOpacity>
)
}
render() {
return (
//..
<View style={{flex: 2, backgroundColor: '#FFF', flexDirection:'row'}} >
<FlatList
data={this.state.searchedItems}
renderItem={this.renderItem}
/>
</View>
//..
try to change this 'renderItem({ item }) {' with this 'renderItem = ({ item }) => {
I am trying to render out a list of object data using FlatList in my React Native component, however I am getting a blank screen without any errors on the console which is why it is rather difficult to get to the bottom of the issue here. The data is made available to the component using Redux-Saga approach and supplied to the FlatList which is showing up a blank screen without any errors. To double check if the FlatList is working fine I did a mockup array in component and passed to the FlatList which renders out the UI as expected. Following is the code I am using here;
=======================================================
class Mobile extends Component {
componentDidMount() {
let { readPostsAction } = this.props;
readPostsAction();
}
renderItem = ({ item }) => {
return (
<View>
<TouchableOpacity onPress={() => this.props.navigation.navigate('HomeDetails', { item })}>
<Card>
<CardItem header>
<Text style={styles.titleHeading}>{item.title}</Text>
</CardItem>
<CardItem cardBody>
<Content style={styles.cardContainer}>
<CustomCachedImage
component={FitImage}
source={{ uri: contentURL(item.attachments[0].url) }}
style={{ width: width, height: 200 }}
/>
<HTML tagsStyles={bodyText} html={reduceStringLength(contentText(item.excerpt))} />
</Content>
</CardItem>
</Card>
</TouchableOpacity>
</View>
)
}
keyExtractor = (item, index) => item.id;
render() {
const { dataSource } = this.props;
console.log('this.props', this.props);
return (
<View>
<FlatList
data={dataSource}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
</View>
);
}
}
function mapStateToProps({ launchAppReducer }) {
return {
isLoading: launchAppReducer.isLoading,
dataSource: launchAppReducer.data
}
}
export default connect(mapStateToProps, { readPostsAction: actions.readPostsAction })(Mobile);
=======================================================
Here is the screenshot of the console showing that the data is available in the component.
Modify your FlatList code and retry
<FlatList
data={dataSource}
extraData={this.props}
keyExtractor={this.keyExtractor}
/>
There was the problem at in the Actions, I was firing readPostsActions instead I should have fired readMobilePostsActions - it works fine now, thank you guys all the all input and help here.
Regards
You just need to add this style in your Flatlist:
<FlatList
style={{height:'100%'}}
data={dataSource}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
I currently have two buttons (No, Yes)( component imported from native-base package) that when pressed should update the state with either 0 or 1 respectively and also toggle between true or false to notify if this field has been filled (by default, neither of the two will be pressed, hence set to false).
I have a handleOnClick() function bound to the "No" button with a debugger to test if I actually do hit it, but once inside this function, I'm not sure how to grab any info for associated components (i.e. the "No" text within the Text component) so I can perform logic to check if "No" or "Yes" was pressed.
If this was done in pure React, I know I can access certain data attributes that I add to DOM elements or traverse the DOM, but I'm not sure how to do this in React Native or if I'm able to add custom props to a built in component that I can then access.
class Toggle extends Component {
constructor() {
super()
this.state = {
selectedOption: '',
isFilled: false
}
this.checkField = this.checkField.bind(this)
this.handleOnClick = this.handleOnClick.bind(this)
}
checkField() {
console.log(this)
// debugger
}
handleOnClick(ev) {
debugger
console.log("I was pressed")
}
render() {
const options = this.props.inputInfo.options //=> [0,1]
const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]
return (
<View style={{flexDirection: 'row'}}>
<View style={styles.row} >
<Button light full onPress={this.handleOnClick}><Text>No</Text></Button>
</View>
<View style={styles.row} >
<Button success full><Text>Yes</Text></Button>
</View>
</View>
)
}
}
If you want to pass information into function, you can pass it when it is called. In your case, you can call your function from arrow function, like so:
<View style={{flexDirection: 'row'}}>
<View style={styles.row} >
<Button light full onPress={() => this.handleOnClick('No')}>
<Text>No</Text>
</Button>
</View>
<View style={styles.row} >
<Button success full><Text>Yes</Text></Button>
</View>
</View>
And in your function
handleOnClick(text) {
debugger
console.log(`${text} pressed`)
}
Have you tried:
render() {
const options = this.props.inputInfo.options //=> [0,1]
const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]
return (
<View style={{flexDirection: 'row'}}>
<View style={styles.row} >
<Button light full onPress={() => this.handleOnClick('No')}><Text>No</Text></Button>
</View>
<View style={styles.row} >
<Button success full onPress={() => this.handleOnClick('Yes')}><Text>Yes</Text></Button>
</View>
</View>
)
}
and
handleOnClick(word) {
this.setState({ selectedOption: word, isFilled: true })
}