A React Native Tree View component!
yarn add react-native-final-tree-view
or
npm install react-native-final-tree-view --save
Firstly, you have to define your data. Example:
const family = [
{
id: 'Grandparent',
name: 'Grandpa',
age: 78,
children: [
{
id: 'Me',
name: 'Me',
age: 30,
children: [
{
id: 'Erick',
name: 'Erick',
age: 10,
},
{
id: 'Rose',
name: 'Rose',
age: 12,
},
],
},
],
},
]
It is required that each node on the tree have its own id
key. Obviously, it should be unique.
The tree nodes are defined in the children
key. They are an array of objects, following the same structure as the parent.
After defining your data, mount the component:
import React from 'react'
import { Text, View } from 'react-native'
import TreeView from 'react-native-final-tree-view'
class App extends React.PureComponent {
state = {
data: [
{
id: 'Grandparent',
name: 'Grandpa',
age: 78,
children: [
{
id: 'Me',
name: 'Me',
age: 30,
children: [
{
id: 'Erick',
name: 'Erick',
age: 10,
},
{
id: 'Rose',
name: 'Rose',
age: 12,
},
],
},
],
},
],
}
componentDidMount() {
console.log(this.treeView.getRawData())
}
render() {
return (
<TreeView
ref={ref => this.treeView = ref}
data={this.state.data}
deleteOnLongPress
renderItem={(item, level) => (
<View>
<Text
style={{
marginLeft: 25 * level,
}}
>
{
item.collapsed !== null ?
<Text>{item.collapsed ? ' > ' : ' \\/ '}</Text> :
<Text> - </Text>
}
{item.name}
</Text>
</View>
)}
/>
)
}
}
export default App
This should display:
And, after a few touches:
Required. The tree data to render;
Optional. The collapsed item height. Defaults to 20
;
Optional. The id
key to refer to. Defaults to id
;
Optional. The children
key to look for. Defaults to children
;
Optional. A callback fired when a node is pressed. The pressed node is sent as the only argument;
Optional. A callback fired when a node is long pressed. The pressed node is sent as the only argument;
Optional. Deletes the pressed node when long pressed;
Required. A function that must return the JSX to render the item. The arguments passed are the child
and
the current level
in the tree, starting from 0
.
You get, for free, a collapsed
key, which could have the possible values:
null
when there are no children for this node;true
when the node is collapsed;false
when the node is expanded.
Example:
renderItem={(item, level) => (
<View>
<Text
style={{
marginLeft: 25 * level,
}}
>
{
item.collapsed !== null ?
<Text>{item.collapsed ? ' > ' : ' \\/ '}</Text> :
<Text> - </Text>
}
{item.name}
</Text>
</View>
)}
Gets the raw, updated, tree data.
Yes, it does. Feel free to modify that awesome state and see the modifications :)
License: MIT