can anyone tell me ,how to use image in a flat-list of react-native? - react-native

class App extends Component {
constructor(props) {
super(props)
this.state = {
list: []
};
}
getList = () => {
const li = [
{ key: "image1", imagelink: "" },
{ key: "image2", imgLink: "imagelink" },
{ key: "image3", imgLink: "imagelink" },
{ key: "image3", imgLink: "imagelink" },
]
this.setState({
list: li
})
}
componentWillMount() {
this.getList()
}
render() {
return (
export default App;

You could just google it, but here is an example:
use FlatList for the list. Pass it the data and a render function.
<FlatList
data={this.data}
renderItem={({ item, index }) => this.renderItem(item, index)}
/>
then create the render function in your component:
renderItem(item, index) {
return (
<Image source={{uri: item.image}}/>
)
}
as an example the data is a component variable:
data = [{image: "link"}, {image: "link"}]

Related

How can I make an entire row clickable in a DetailsList component? (office-ui-fabric)

I've been using the DetailsList component but haven't found a way to make an entire row clickable - is there a sample code snippet or pointers on how this can be achieved?
https://developer.microsoft.com/en-us/fabric#/components/detailslist
Overriding onRenderRow worked for me.
const _columns: IColumn[] = [
{
key: 'name',
name: 'Name',
fieldName: 'name',
minWidth: 100,
maxWidth: 200,
isResizable: true
},
{
key: 'value',
name: 'Value',
fieldName: 'value',
minWidth: 100,
maxWidth: 200,
isResizable: true,
}
];
const _items = Array.apply(null, Array(10)).map((_: any, num: number) => ({
key: num.toString(),
name: `Item ${num.toString()}`,
value: num.toString()
}));
class Content extends React.Component {
private _renderRow(props: Fabric.IDetailsRowProps, defaultRender: any): JSX.Element {
return (
<Fabric.DetailsRow {...props} onClick={() => alert('click')}/>
);
}
public render() {
return (
<Fabric.Fabric>
<Fabric.DetailsList
items={ _items }
columns={ _columns.concat(..._columns, ..._columns, ..._columns) }
onRenderRow={this._renderRow}
/>
</Fabric.Fabric>
);
}
}
ReactDOM.render(
<Content />,
document.getElementById('content')
);
Here is th e single click solution,
Use onActiveItemChanged prop like:
const _onActiveItemChanged = (item): void => {
alert(`Item invoked: ${JSON.stringify(item)}`);
};
here is the DetailList
<DetailsList
items={assessmentList}
compact={false}
columns={columns}
onActiveItemChanged={_onActiveItemChanged }
/>
Please onItemInvoked Property and method. But it works on double click. I am also looking for single click solution
const onItemInvoked = (item): void => {
alert(`Item invoked: ${JSON.stringify(item)}`);
};
<DetailsList
items={assessmentList}
compact={false}
columns={columns}
selectionMode={SelectionMode.multiple}
getKey={_getKey}
setKey="multiple"
layoutMode={DetailsListLayoutMode.justified}
checkboxVisibility={CheckboxVisibility.hidden}
isHeaderVisible={true}
selectionPreservedOnEmptyClick={false}
enterModalSelectionOnTouch={true}
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
checkButtonAriaLabel="Select Checkbox"
onRenderRow={onRenderRow}
onItemInvoked={onItemInvoked}
onRenderDetailsHeader={(headerProps, defaultRender) => {
return (
<Sticky
stickyPosition={StickyPositionType.Header}
isScrollSynced={true}
stickyBackgroundColor="transparent"
>
<div className="text-center">{defaultRender(headerProps)}</div>
</Sticky>
);
}}
/>
Use onRenderRow and cloneElement to attach an onClick listener:
import React, { useCallback, cloneElement } from 'react';
import { DetailsList } from '#fluentui/react';
const Component = () => {
const onItemInvoked = useCallback( ( item ) => {
console.log( item );
}, [] );
const onRenderRow = useCallback( ( row, defaultRender ) => {
return cloneElement( defaultRender( row ), { onClick: () => onItemInvoked( row.item ) } )
}, [ onItemInvoked ] );
return (
<DetailsList
onRenderRow={ onRenderRow }
/>
);
};

How to make dynamic checkbox in react native

I am making a react native application in which i need to make checkbox during runtime.I means that from server i will get the json object which will have id and label for checkbox.Now i want to know that after fetching data from server how can i make checkbox also how can i handle the checkbox , i mean that how many number of checkbox will be there it will not be static so how can i declare state variables which can handle the checkbox.Also how can i handle the onPress event of checkbox.Please provide me some help of code .Thanks in advance
The concept will be using an array in the state and setting the state array with the data you got from the service response, Checkbox is not available in both platforms so you will have to use react-native-elements. And you can use the map function to render the checkboxes from the array, and have an onPress to change the state accordingly. The code will be as below. You will have to think about maintaining the checked value in the state as well.
import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox } from 'react-native-elements';
export default class Sample extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: 1, key: 'test1', checked: false },
{ id: 2, key: 'test1', checked: true }
]
};
}
onCheckChanged(id) {
const data = this.state.data;
const index = data.findIndex(x => x.id === id);
data[index].checked = !data[index].checked;
this.setState(data);
}
render() {
return (<View>
{
this.state.data.map((item,key) => <CheckBox title={item.key} key={key} checked={item.checked} onPress={()=>this.onCheckChanged(item.id)}/>)
}
</View>)
}
}
Here's an example how you can do this. You can play with the code, to understand more how it's working.
export default class App extends React.Component {
state = {
checkboxes: [],
};
async componentDidMount() {
// mocking a datafetch
setTimeout(() => {
// mock data
const data = [{ id: 1, label: 'first' }, { id: 2, label: 'second' }];
this.setState({
checkboxes: data.map(x => {
x['value'] = false;
return x;
}),
});
}, 1000);
}
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{JSON.stringify(this.state)}
</Text>
{this.state.checkboxes.length > 0 &&
this.state.checkboxes.map(checkbox => (
<View>
<Text>{checkbox.label}</Text>
<CheckBox
onValueChange={value =>
this.setState(state => {
const index = state.checkboxes.findIndex(
x => x.id === checkbox.id
);
return {
checkboxes: [
...state.checkboxes.slice(0, index),
{ id: checkbox.id, label: checkbox.label, value },
...state.checkboxes.slice(index+1),
],
};
})
}
value={checkbox.value}
key={checkbox.id}
/>
</View>
))}
</View>
);
}
}

How to access a row using FlatList keyExtractor in react-native

Is there any way to access a row using key, set using keyExtractor in FlatList.
I using FlatList inorder to populate by data, i need to get a row separately using it's key, inorder to update that row without re-render the entire view.
on componentWillMount i populated datalist array using an api call.
dummy array look this
[{id:"Usr01",title:"Name1"},{id:"Usr02",title:"Name2"},...]
while press on any row i get it's id, i need to access that row using it's key.
let dataitem = this.state.datalist[id];
while i console dataitem i get undefined
i set id as the key in keyExtractor, is there any way to do the same.
My code look like this
FlatListScreen.js
export default class FlatListScreen extends Component {
constructor(props)
{
super(props);
this.state={
datalist: [],
}
}
componentWillMount() {
ApiHandler.getlistitem('All').then(response =>{
this.setState({datalist: response});
});
}
_keyExtractor = (item, index) => item.id;
_onPressItem = (id) => {
let dataitem = this.state.datalist[id];
const { name } = dataitem
const newPost = {
...dataitem,
name: name+"01"
}
this.setState({
datalist: {
...this.state.datalist,
[id]: newPost
}
})
};
_renderItem ({ item }) {
return (
<MyListItem
id={item.id}
onPressItem={this._onPressItem}
title={item.title}
/>
)
}
render() {
return (
<FlatList
data={this.state.datalist}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
}
}
MyListItem.js
export default class MyListItem extends Component {
constructor(props) {
super(props)
this.state = {
title: '',
id: ''
}
}
componentWillMount() {
const { title, id } = this.props
this.setState({ title, id })
}
componentWillReceiveProps(nextProps) {
const { title, id } = nextProps
this.setState({ title, id })
}
shouldComponentUpdate(nextProps, nextState) {
const { title} = nextState
const { title: oldTitle } = this.state
return title !== oldTitle
}
render() {
return (
<View>
<TouchableOpacity onPress={() =>this.props.onPressItem({id:this.state.id})}>
<View>
<Text>
{this.props.title}
</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
I think changing
onPressItem({id:this.state.id});
to
onPressItem(this.state.id); in your child component
OR
_onPressItem = (id) => { }
to
_onPressItem = ({id}) => { }
in your parent component will solve the issue.
As you are sending it as an object from child to parent and you can access it like this also
let dataitem = this.state.datalist[id.id];

React Native - setState from array

I'm trying create-react-native-app for the first time and I want to change text on varying time intervals. But my code only gives me the last item of the array.
import React from 'react';
import { Text } from 'react-native';
const blinkText = [
{
text: "A",
time: 500,
},
{
text: "B",
time: 1000,
},
{
text: "C",
time: 1000,
},
];
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.interval = setInterval(() => {
blinkText.map(value => this.setState(value))
}, this.state.time);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return(
<Text>{this.state.text}</Text>
);
}
}
I know I have my problem at componentDidMount() but I could not think of a way. Please take a look at my code and modify. Thanks.
Try this
componentDidMount(){
blinkText.map(e => {
setTimeout(() => {
this.setState(
prevState => ({
text: [...prevState.text, e]
});
);
}, e.time);
});
}
Note that, this.stat.text is an array, so you should render it inside your render() method by applying map()
Example:
{ this.state.text.map((e, i) => {
return (
<Text key={i}>{e}</Text>
);
})}

React-native States

I declare state at constructor and try to call it from renderScene but this.state is always null what is wrong?
My code is;
var _=require('underscore');
class ReactNotes extends React.Component {
constructor (props) {
super(props);
this.state = {
selectedNote: {title:"", body:""},
notes: {
1: {title: "Note 1", body: "body", id: 1},
2: {title: "Note 2", body: "body", id: 2}
}
};
} render () {
return (
<Navigator initialRoute={{name: 'home'}}
renderScene={this.renderScene}
navigationBar=
{
<Navigator.NavigationBar
routeMapper={NavigationBarRouteMapper}
style={styles.navBar}
/>
}
/> );
}
renderScene (route, navigator) {
switch (route.name) {
case 'home':
return (
<HomeScreen navigator={navigator} notes= {_(this.state.notes).toArray()} onSelectNote={(note) => navigator.push({name:"createNote", note: note})}/>
);
case 'createNote':
return (
<NoteScreen note={this.state.selectedNote}
onChangeNote={(note) => this.updateNote(note)}/>
);
} }
}
The output is as follows:
You can bind your function with arrow function
renderScene = (route, navigator) => {
//...
}
//then call your function in your navigator as
renderScene={this.renderScene}
or
// You can use bind() to preserve `this`
renderScene={this.renderScene.bind(this)}>
// Or you can use arrow function this way
renderScene={() => this.renderScene()}>