• Resolved Alex Kozack

    (@cawa-93)


    I’m working on a form designer.

    I have an independent RadioBlock and ContainerBlock.

    The ContainerBlock can contain any content, including any number of RadioBlocks.

    I need to somehow set the same name attribute for all RadioBlocks inside a common ContainerBlock. The name has no reference to anything. It is just a random string. However, it must be identical for all RadioBlocks in shared container.

    Can a ContainerBlock pass some arbitrary value in it through the tree to all internal blocks?

    Can a RadioBlock in the editor somehow get information from its neighbors within a single container?

Viewing 1 replies (of 1 total)
  • 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.

Viewing 1 replies (of 1 total)
  • The topic ‘How to share some static value between all neighboring blocks of the same type?’ is closed to new replies.