skip to Main Content

I’m using a Map to store the state of my component. Within this component, I have 3 groups, and in each group I have radio buttons. I have this array so that I can set values by default:

const defaultOptions = [
    { label: "Mark", value: "mark" },
    { label: "Steve", value: "steve" },
    { label: "Paul", value: "Paul" }
  ];

How can I set values by default using this array?

Here’s live DEMO

3

Answers


  1. In your code there is no connection between the post (which has all the radio buttons) and the default ones. You can rely on luck and assume that first item of array is related to the Group A, and so on. But that is such an awful thing to do. I would not recommend doing any workaround to the current example. and think about another solution.

    Login or Signup to reply.
  2. you must use the checkedprop

        <article>
          {showGroup && (
            <div>
              {post.fields?.map((field: any, idx: number) => {
                const itemsSelected = checkboxStates
                .get(post.label)
                ?.some((o) => o.label === field.name)
                const isChecked =
                  itemsSelected !== null || itemsSelected !== undefined ? itemsSelected : defaultOptions.some(item => item.value === field.value);
                return (
                  <div key={idx}>
                    <input
                      type="radio"
                      name={post.label}
                      value={field.value}
                      checked={isChecked}
                      onChange={(e) =>
                        handleRadiobuttonChange(field, e.target.checked)
                      }
                    />
                    <span>{field?.name}</span>
                    <br />
                  </div>
                );
              })}
            </div>
          )}
        </article>
    
    
    Login or Signup to reply.
  3. You can create the Map based on the array of defaults like so:

    // in the App component
    useEffect(() => {
        const newPosts = someJson;
        setPosts(newPosts);
        setSearchResults(newPosts);
        setCheckboxStates(
          new Map(defaultOptions.map(o => 
            [newPosts.find(p => p.fields.some(f => f.name === o.label)).label, [o]]))
        );
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search