bootstrap4 style tree for react
npm install react-bootstrap4-treejavascript
$ npm install react-bootstrap4-tree
`
$3
Include the correct styles, it's mainly just bootstrap but we add a few tweaks as well.
`html
`
OR
`javascript
npm install bootstrap
`
In index.js:
`javascript
import 'bootstrap/dist/css/bootstrap.css'
`
Then, a basic initialization would look like.
`javascript
React.render(
,
document.getElementById('treeview')
);
`
Data Structure
In order to define the hierarchical structure needed for the tree it's necessary to provide a nested array of JavaScript objects.
You can define your custom data in the tree data.
Example
`javascript
let data = [
{
text: 'a1',
customData: {
id: '1'
},
nodes: [
{
text: 'a1-a1',
customData: {
id: '2'
},
nodes: []
}
]
},
{
text: 'a2',
customData: {
id: '3'
},
nodes: [
{
text: 'a2-a1',
customData: {
id: '4'
},
nodes: [
{
text: 'a2-a1-a1'
},
{
text: 'a2-a1-a2'
}
]
}
]
},
{
text: 'a3',
customData: {
id: '7',
other: 'other'
},
nodes: [
{
text: 'a3-a1',
customData: {
id: '9',
another: 'another'
},
nodes: [
{
text: 'a2-a1-a1',
nodes: [
{
text: 'a2-a1-a1'
},
{
text: 'a2-a1-a2'
}
]
},
{
text: 'a2-a1-a2'
}
]
},
{
text: 'a3-a2'
}
]
},
];
`
If you want to do more, here's the full node specification
`javascript
{
text: "Text 1",
color: "#000000",
backgroundColor: "#FFFFFF",
showBorder: true,
showSelect: true,
state: {
expanded: true,
selected: true
},
customData: {
},
nodes: [
{},
...
]
}
`
$3
The following properties are defined to allow node level overrides, such as node specific colors and border.
#### text
String Mandatory
The text value displayed for a given tree node.
#### color
String Optional
The foreground color used on a given node, overrides global color option.
#### backgroundColor
String Optional
The background color used on a given node, overrides global color option.
#### state
Object Optional
Describes a node's initial state.
#### state.expanded
Boolean Default: false
Whether or not a node is expanded i.e. open. Takes precedence over global option levels.
#### state.selected
Boolean Default: false
Whether or not a node is selected.
Options
Options allow you to customise the treeview's default appearance and behaviour. They are passed to the react component as properties on initialization.
`javascript
// Example: initializing the treeview
// with a background color of green
// with onExpand and onSelect function
let onExpand = function(nodeData, treeData) {
console.log(nodeData);
console.log(treeData);
}
let onSelect = function(nodeData, treeData) {
console.log(nodeData);
console.log(treeData);
}
React.render(
,
document.getElementById('treeview')
);
``