Reputation:
https://codesandbox.io/s/0prxxxvy0n
class App extends React.Component {
render() {
console.log("App---->");
return (
<StickyContainer>
{/* Other elements can be in between `StickyContainer` and `Sticky`,
but certain styles can break the positioning logic used. */}
<div>
I am sticky------------------------------------------------------->
</div>
<Sticky>
{({
style,
// the following are also available but unused in this example
isSticky,
wasSticky,
distanceFromTop,
distanceFromBottom,
calculatedHeight
}) => <header style={style}>{}</header>}
</Sticky>
<SearchBar />
<div>I am sticky</div>
<WholeText />
<UploadDocuments />
<VerticalLinearStepper />
{/* ... */}
</StickyContainer>
);
}
}
Upvotes: 1
Views: 1196
Reputation: 1532
As the documentation says, you need to put your div within the render callback of the component, i.e.
class App extends React.Component {
render() {
console.log("App---->");
return (
<StickyContainer>
<Sticky>
{({ style }) => <div style={style}>I am sticky</div>}
</Sticky>
<SearchBar />
<div>I am sticky</div>
<WholeText />
<UploadDocuments />
<VerticalLinearStepper />
{/* ... */}
</StickyContainer>
);
}
}
A "render callback" in this case just means that the child of the <Sticky>
component needs to be a function that returns what should be rendered. This allows the parent to pass additional information to use in the rendering of the child via the arguments of the function. The syntax for specifying a function as a child is:
<Parent>{/*function goes here*/}</Parent>
In the example above, the function part is ({ style }) => <div style={style}>I am sticky</div>
which assumes the parameter that will be passed to the function will be an object with a style
property and then the function returns a div element using that style.
If you look at the react-sticky code you'll find that in its render
method it does the following:
const element = React.cloneElement(
this.props.children({
isSticky: this.state.isSticky,
wasSticky: this.state.wasSticky,
distanceFromTop: this.state.distanceFromTop,
distanceFromBottom: this.state.distanceFromBottom,
calculatedHeight: this.state.calculatedHeight,
style: this.state.style
}),
{
ref: content => {
this.content = ReactDOM.findDOMNode(content);
}
}
);
When it calls this.props.children(...)
, that executes the function you specified as a child and you can see that the last property on the object it passes to the function is the style
property.
Upvotes: 2