Reputation: 35
I am using the CircleType.js library which allows you to curve a string of text/render it as a circle. However, I am very new to React and I'm not sure how to use the library in React. I created a functional component and used the documentation provided in the CircleType page to create... but I keep getting a 'TypeError: Cannot read property 'innerHTML' of null' error.
import React, {useEffect} from 'react'
import CircleType from 'circletype'
function RotatingCircle() {
// const circleOfSkills = new CircleType(document.getElementById('rounded-text'))
// .radius(100)
// useEffect(() => {
// return () => circleOfSkills.mount()
// }, [circleOfSkills])
return (
<p className="circle" id="rounded-text">
AND THE WORLD KEEPS GOING AROUND AND AROUND AND AROUND
</p>
)
}
export default RotatingCircle
I read that I might need to use refs but I'm really not sure how to use it as all examples I see use class components. Another forum I saw suggested using useEffect, but I'm clearly not using it correctly.
How do I reference DOM elements in a functional component?
Upvotes: 2
Views: 751
Reputation: 684
Here is an example of CircleType implementation with React useRef
hook. Avoid using getElementById
for DOM manipulation as it is not the React way.
Sample code and CodeSandbox link:
import React, { useEffect, useRef } from "react";
import "./styles.css";
import CircleType from "circletype";
export default function App() {
const circleInstance = useRef();
useEffect(() => {
new CircleType(circleInstance.current).radius(100);
}, []);
return (
<div className="App">
<div ref={circleInstance}>abcdef</div>
</div>
);
}
Upvotes: 2
Reputation: 71
try this
useEffect(() => {
const circleOfSkills = new CircleType(document.getElementById('rounded-text'))
.radius(100)
return circleOfSkills.mount()
}, []);
Upvotes: 2
Reputation: 405
When using react I'd avoid using getElementbyID inside your components. Defining a root in your index.html and then linking it in index.js
by
import React from "react";
import ReactDOM from "react-dom";
import App from "./App"; //App is your base react component
ReactDOM.render(
<App />
document.getElementById("root")
);
It will save you headaches like this and others in the future. React components are like a tree and by defining only one root you are utilizing what react was built for.
Upvotes: 0
Reputation: 132
Try moving the const inside useEffect like this:
useEffect(() => {
const circleOfSkills = new CircleType(document.getElementById('rounded-text'))
.radius(100)
return () => circleOfSkills.mount()
}, []);
Calling getElementById outside of useEffect will give you null error because the element is not yet rendered on the page.
Upvotes: 1