Is there any good way to shallow compare element?
Is there any good way to shallow compare two elements?
I have two variables a and b and I want to shallow compare their value like below:
let myFunc = ()=>alert('!');
let a = <a onClick={myFunc}>123</a>;
let b = <a onClick={myFunc}>123</a>;
let c = <a onClick={()=>alert('!')}>123</a>;
isElementSwallowEqual(a, b); // return true;
isElementSwallowEqual(a, c); // return false;
Since React.createElement creates plain object, I just implement this method by special compare the children value in props. Did React provide some function to do this job? Thank you.
What you mean is this one? shallowCompare 😂 it is just inner-used, not be exposed
Do you need this functionality in product code or in a test? Have you considered enzyme's shallow rendering? https://github.com/airbnb/enzyme
@zjuasmn can you expand on your use case? Why do you want to shallowly compare two React elements? If testing then @finnigantime's recommendation for Enzyme is a good one. If you're trying to compare elements after an update then you typically would compare props and state instead of the element itself.
In any case, we use this issue tracker for bug reports and feature requests only. If you have a support or usage question we recommend using one of the many communities oriented around that, such as StackOverflow, Reactiflux, or discuss.reactjs.org.
Hope that helps!