ReactJS进度条组件中document.getElementById()无法获取DOM元素的报错问题
Hey there! Let's break down why you're running into this error and get your progress bar working smoothly.
The Root Cause
When your MyProgressBar function runs, the JSX you return hasn't been rendered to the actual browser DOM yet. That means when you call document.getElementById("hello"), the element doesn't exist in the DOM tree—so it returns null, and trying to access null.style throws the error you're seeing.
On top of that, React is built around managing UI changes through props and state instead of manual DOM manipulation, so using document.getElementById here goes against React's core paradigm.
Solution 1: Use React's useRef Hook (For Safe DOM Access)
If you need direct access to the DOM element, use React's useRef hook paired with useEffect to ensure you only interact with the element after it's been mounted:
import { useRef, useEffect } from 'react'; import './MyProgressBar.css' const MyProgressBar = (props) => { const value = props.value; // Create a ref to hold the progress bar element const progressRef = useRef(null); // This effect runs after component mounts, and whenever `value` updates useEffect(() => { // Guard clause to avoid null errors if (progressRef.current) { progressRef.current.style.width = `${value}%`; } }, [value]); // Re-run when `value` changes return ( // Note: Use `className` instead of `class` in React JSX <div className="progress"> <div ref={progressRef} className="color"></div> </div> ) } export default MyProgressBar
Solution 2: Declarative Style Binding (The React-First Approach)
Even better—skip manual DOM work entirely and bind the style directly in your JSX. This is the cleanest, most idiomatic way to handle UI updates in React:
import './MyProgressBar.css' const MyProgressBar = (props) => { const value = props.value; return ( <div className="progress"> <div className="color" // Bind width directly to the `value` prop style={{ width: `${value}%` }} ></div> </div> ) } export default MyProgressBar
Quick Reminder
Don't miss this detail: In React JSX, we use className instead of the HTML class attribute—since class is a reserved keyword in JavaScript.
内容的提问来源于stack exchange,提问作者Jorge Sánchez

