> I don't know why @NephiBalinski deleted his answer, but here it is just for reference, since I thought it was useful. It basically uses a mix of my second snippet and what @Mulan ended up coming up with.
---
## 1. The React Context way
One way to solve this is using React Context. Here is the revised and updated code using React Context:
<!-- begin snippet: js hide: false console: true babel: true -->
<!-- language: lang-js -->
const FootnotesContext = React.createContext(null);
function FootnotesProvider({ children }) {
const [footnotes, setFootnotes] = React.useState([]);
const footnotesRef = React.useRef([]);
function addFootnote(html) {
footnotesRef.current = [...footnotesRef.current, html];
setFootnotes([...footnotesRef.current, ]);
}
function totalFootnotes() {
return footnotes.length;
}
return (
<FootnotesContext.Provider value={{ footnotes, addFootnote, totalFootnotes, }}>
{children}
</FootnotesContext.Provider>
);
}
function useFootnotes() {
const context = React.useContext(FootnotesContext);
if (!context) throw new Error('`useFootnotes` must be used within a `FootnotesProvider`.');
return context;
}
function Article() {
return (
<FootnotesProvider>
<article>
<p>
The <FootNote html="Footnote 1" /> article content here <FootNote html="Footnote 2" />.
</p>
<hr />
<FootNotesContainer />
</article>
</FootnotesProvider>
);
}
function FootNotesContainer() {
const { footnotes } = useFootnotes();
return (
<div id="footnotes-container">
<h2>Footnotes</h2>
<h3>Total Footnotes: {footnotes.length}</h3>
{footnotes.map((f, i) => (
<div className="footnote" key={i}>
<a href={`#footnote-sup-${i + 1}`} id={`footnote-${i}`}>
{i + 1}
</a>:
<p>{f}</p>
</div>
))}
</div>
);
}
function FootNote({ html }) {
const { footnotes, addFootnote, totalFootnotes } = useFootnotes();
// const footnoteRef = React.useRef(null);
const [index, setIndex] = React.useState(0)
React.useEffect(() => {
addFootnote(html);
}, []);
React.useEffect(() => {
setIndex(footnotes.indexOf(html) + 1)
}, [footnotes])
return (
<sup
className="footnote-sup"
// ref={ref => footnoteRef.current = ref}
>
<a
href={`#footnote-${index}`}
id={`footnote-sup-${index}`}
>
{index}
</a>
</sup>
)
}
ReactDOM.createRoot(document.getElementById("root")).render(<Article />);
<!-- language: lang-css -->
.footnote {
display: flex;
gap: 4px;
align-items: center;
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<!-- end snippet -->
### Key changes
- We added a footnotesRef to ensures that footnotes are added sequentially.
- We restructured the FootNote component to correct render footnote numbering.
- We corrected the links in FootNotesContainer.
- We didn't use DOM manipulation!
This should fix the footnotes issue.
## 2. The generator way (not recommended)
Another approach is using ES6 generator functions. Here is an example of a basic generator function:
```js
function* genId() {
var index = 0;
while (true)
yield index++;
}
}
let gen = genId();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
```
Here is the revised and updated code:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function Article() {
return (
<article>
<p>The<FootNote html="Footnote 1" /> article content here<FootNote html="Footnote 2" />.</p>
<FootNotesContainer />
</article>
);
}
function FootNotesContainer() {
return (
<div id='footnotes-container'>
<h2>Footnotes</h2>
</div>
);
}
function* generateId() {
let idCounter = 1;
while (true) {
yield idCounter++;
}
}
const gen = generateId();
function useFootnoteId() {
const [id, setId] = React.useState(0);
React.useEffect(() => {
setId(gen.next().value);
}, [gen]);
return id;
}
function FootNote({ html }) {
const footNoteLink = useFootnoteId();
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/regenerator-runtime@0.14.1/runtime.min.js"></script>
<div id="root"></div>
<!-- end snippet -->
### Key changes
- We no longer use previousFootnotes.length to calculate what footNoteLink is. Instead we use useFootnoteId and generateId functions.
- Note: We've removed DOM reads, so actions like deleting footnotes may require extra steps.
- We implemented a cleanup function in FootNotesContainer to avoid unnecessary footnote creation due to excessive re-renders.
Now footnotes should work the way you want them to.
That's [*property spread notation*][1]. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "[JSX spread attributes][2]" even though you could do it elsewhere, too, not just attributes).
`{...this.props}` *spreads out* the "own" enumerable properties in `props` as discrete properties on the `Modal` element you're creating. For instance, if `this.props` contained `a: 1` and `b: 2`, then
<Modal {...this.props} title='Modal heading' animation={false}>
would be the same as
<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
But it's dynamic, so whatever "own" properties are in `props` are included.
Since `children` is an "own" property in `props`, spread will include it. So if the component where this appears had child elements, they'll be passed on to `Modal`. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a `children` property in the opening tag. Example:
<!-- begin snippet: js hide: true console: true babel: true -->
<!-- language: lang-js -->
class Example extends React.Component {
render() {
const { className, children } = this.props;
return (
<div className={className}>
{children}
</div>
);
}
}
ReactDOM.render(
[
<Example className="first">
<span>Child in first</span>
</Example>,
<Example className="second" children={<span>Child in second</span>} />
],
document.getElementById("root")
);
<!-- language: lang-css -->
.first {
color: green;
}
.second {
color: blue;
}
<!-- language: lang-html -->
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<!-- end snippet -->
Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:
this.setState(prevState => {
return {foo: {...prevState.foo, a: "updated"}};
});
That replaces `this.state.foo` with a new object with all the same properties as `foo` except the `a` property, which becomes `"updated"`:
<!-- begin snippet: js hide: true console: true babel: false -->
<!-- language: lang-js -->
const obj = {
foo: {
a: 1,
b: 2,
c: 3
}
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);
<!-- language: lang-css -->
.as-console-wrapper {
max-height: 100% !important;
}
<!-- end snippet -->
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
[2]: https://reactjs.org/docs/jsx-in-depth.html#spread-attributes