Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Cómo obtener el ancho de un elemento de reacción

Estoy tratando de crear una entrada de rango que muestre una información sobre herramientas justo encima del control deslizante.

Revisé algunos ejemplos de Vanilla JS en línea y parece que necesito tener el ancho del elemento para lograrlo.

Entonces, me preguntaba cómo obtener el ancho de los elementos.

Más o menos el equivalente del método JQuery $(element).width()

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

 class MyComponent extends Component { constructor(props){ super(props) this.myInput = React.createRef() } componentDidMount () { console.log(this.myInput.current.offsetWidth) } render () { return ( // new way - as of React@16.3 <div ref={this.myInput}>some elem</div> // legacy way // <div ref={(ref) => this.myInput = ref}>some elem</div> ) } }
over 4 years ago · Santiago Trujillo Report

0

Con ganchos :

 const MyComponent = () => { const ref = useRef(null); useEffect(() => { console.log('width', ref.current ? ref.current.offsetWidth : 0); }, [ref.current]); return <div ref={ref}>Hello</div>; };
over 4 years ago · Santiago Trujillo Report

0

Esta es básicamente la respuesta de Marco Antônio para un enlace personalizado de React, pero modificado para establecer las dimensiones inicialmente y no solo después de un cambio de tamaño.

 export const useContainerDimensions = myRef => { const getDimensions = () => ({ width: myRef.current.offsetWidth, height: myRef.current.offsetHeight }) const [dimensions, setDimensions] = useState({ width: 0, height: 0 }) useEffect(() => { const handleResize = () => { setDimensions(getDimensions()) } if (myRef.current) { setDimensions(getDimensions()) } window.addEventListener("resize", handleResize) return () => { window.removeEventListener("resize", handleResize) } }, [myRef]) return dimensions; };

Usado de la misma manera:

 const MyComponent = () => { const componentRef = useRef() const { width, height } = useContainerDimensions(componentRef) return ( <div ref={componentRef}> <p>width: {width}px</p> <p>height: {height}px</p> <div/> ) }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!