Before I start answering, this component has a lot going on in it and I’m not going to debug it for you, especially since it’s not built on standard React practices making it very hard for me to read. So, I’m going to give you some tips based on a few things I pulled out to help get you into standard practices. Hopefully in doing so, you can figure out where your issue is.
You should be using const
and let
, there’s no good reason to use var
if you’re using other ES6 features. Just forget var
exists. It’s only good for hoisting. You’ll most likely never need or want your variables hoisted if your code is designed right.
Your render
function should be very very light. Building other methods that render is fine, it would look something like this:
class TreeNode extends Component {
someOtherThing = () => {
return <span>Hello World</span>
}
render() {
return <div>{this.someOtherThing()}</div>
}
}
You should not be doing all the above in the render method. But, honestly with how much you have going on in this you should really be moving most of this to their own components to simplify your code. More components are better than big components. They are easier to read, support, and expand. Don’t be afraid of making new components, be afraid of shoving too much into one.
Below is not the way you should be conditionally rendering in React. Don’t feel bad though I even catch myself doing this sometimes without thinking.
if (!this.props.visible) {
style = {
display: 'none'
};
}
The way you’d do this in react, is to just not render the element via a little bit of inline JSX. So, taking the short example class I did above you’d do something like this:
render() {
return (
<div>
{this.props.visible && this.someOtherThing()}
</div>
)
}
This works because if the left side of the boolean argument is false, then the right side will not be called thus not rendering the component. This the most preferred way to do it in React, because it’s the cleanest.
Here, you can use destructuring:
var node = this.props.node;
var options = this.props;
var treeType = this.props.type;
Should be:
const {node, type, ...rest} = this.props
then you can use the variables just like you normally would. The rest
variable contains all the things not explicitly pulled out of this.props
, which replaces your options variable. The ...
is called the spread operator. It works both ways. It’s very cool and incredibly useful.
Also, classnames might be a useful library for you to use. It will keep you from doing the gross if/else statements to conditionally set classes and automatically handles undefined
and null
values, where as normally the actual words undefined
/null
would be passed to the className
prop. It’s used by most React apps that use classes.