1

I want to apply getElementsByClassName to a element with dynamic name assigned by CSS modules in React.js. For example, if I named a class as 'firstLink' using className={styles.firstLink} in a file named RegisterPage.js, the resulting name for the class is:

<a href="" class="RegisterPage_firstLink__1Ozd-"></a>

The __1Ozd bit is random. How can I apply getElementsByClassName in this situation ?

1
  • what is your use case? why do you need to perform dom query in react? you can add your specific class to react elements Commented Nov 3, 2020 at 23:11

2 Answers 2

4

CSS modules provides key-value object which you can use in the code. Key is class name defined by you, value is generated class name.

import React from 'react'
import style from './style.module.css'

export default function Component() {
  React.useEffect(() => {
    console.log(document.getElementsByClassName(style.firstLink))
  }, [])

  return <div className={style.firstLink} />
}

And I believe there can't be any reason to use vanilla js functions like getElementsByClassName, using state and in some cases using refs should cover all cases, example:

import React from 'react'

export default function Component() {
  const ref = React.useRef()

  React.useEffect(() => {
    console.log(ref.current) // Will output dom element
  }, [])

  return <div ref={ref} />
}

After some thinking, perhaps there are old-school libraries which can accept root element only by class name.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the tip, man. I'll be using refs from now on. You mentioned states can also be used in this situation ? Could you give an example ? How would I assign the component to a state ?
Idea of React is to not couple with DOM elements at all, that's why react is so awesome and other frameworks are nice too! Why do you need to access DOM element? Once I know I could provide example using state
It's for a form validation. If the user didn't write anything in an input field and tries to submit it, the border of the input must turn red and display an error message like "you must type your name here", for example. So basically, I want to do something like style.border = 'solid red 2px'. It worked with the useRef, but just curious how to do it with state. By the way, if I have 4 inputs, do I have to create a ref for each one of them ?
Ref is a tool for rare exceptional cases, not for validation. Validation is quite a basic thing. Easy and dirty validation: you can define [name, setName] = React.useState(''), then put it to input:<input value={name} onChange={e => setName(e.target.value)}> and then in case if name is empty string you can show such message. Correct way is to use libraries, I prefer react-hook-form + yup, formik is also good. It's correct because it requires minimum code and looks clean, but it's more complex, requires to read docs
Ok, but if I have the state holding the value of the input like <input value={name} onChange={e => setName(e.target.value)}>, is there any way I can change the input style properties through that, like defining the border color to red ?
|
1

In react, behaviors such as you wanted is termed Refs, see this.

If you are building functional component do this:

const {useRef} = React

const Component =>{
   styelRef = useRef()
   //refer to your anchor tag style here which should be called className
   const styleFnc=()=>{
     styleRef.current.className = "__1Ozd"
   }
   return(
     <a ref={styleRef} href="...." className={`RegisterPage_firstLink${styelFnc}`}></a>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.