Yes, you can achieve this behavior by using React context to share the common value (in this case, the random string for the name
attribute) between all RadioBlocks within a single ContainerBlock. Here’s an example of how to implement this:
First, create a context for the random string value:
import React from 'react';
const RadioGroupNameContext = React.createContext(null);
export default RadioGroupNameContext;
In your ContainerBlock component, wrap the children with a RadioGroupNameContext.Provider
and generate a random string for the value
prop:
import React, { useState, useEffect } from 'react';
import RadioGroupNameContext from './RadioGroupNameContext';
function ContainerBlock({ children }) {
const [randomName, setRandomName] = useState('');
useEffect(() => {
setRandomName(generateRandomString());
}, []);
// Function to generate a random string for the name attribute
function generateRandomString() {
return Math.random().toString(36).substr(2, 8);
}
return (
<RadioGroupNameContext.Provider value={randomName}>
<div className="container-block">{children}</div>
</RadioGroupNameContext.Provider>
);
}
export default ContainerBlock;
In your RadioBlock component, use the RadioGroupNameContext
to get the shared name
attribute value from the nearest ContainerBlock:
import React, { useContext } from 'react';
import RadioGroupNameContext from './RadioGroupNameContext';
function RadioBlock() {
const groupName = useContext(RadioGroupNameContext);
return (
<div className="radio-block">
<input type="radio" name={groupName} />
{/* ... other elements */}
</div>
);
}
export default RadioBlock;
Now, all RadioBlocks within the same ContainerBlock will have the same random string value for the name
attribute, which is shared through the context.