The checkbox appears to have selected values, yet the selected options are not visibly displayed

UPDATE

I have been utilizing this specific file in order to dynamically generate a list of tags using the code provided below.

import React from "react";


class TagElement extends React.Component{

    updateCheck(e){
        var v = (e.target.checked)? e.target.value : false
        this.props.checkEvent(v)
    }

    render(){
        const tag_name = this.props.tagElement;
        const tag_id = Math.random();
        return(
            <div className="form-check">
                <input className    =   "form-check-input" 
                    type            =   "checkbox" 
                    defaultChecked  =   {this.props.checked}
                    name            =   {tag_name}
                    id              =   { tag_id }
                    onChange        =   {(e) => this.updateCheck(e)}
                    />
                <label className="form-check-label" htmlFor={tag_id}>
                    { tag_name  + " " + this.props.checked }
                </label>
            </div>
        )
    }
}

class TagTree extends React.Component{

    state = {
        key : "",
        val : [],
        display : "none"
    }

    onCheck(v){
        this.setState({ display : v? "block" : "none"})
    }

    componentDidMount(){

        const tagkey = Object.keys(this.props.tagTree)[0]
        const tagval = this.props.tagTree[tagkey]
        const includedActiveList = this.props.activeTags.includes(tagkey)

        this.setState(
            {
                key : tagkey,
                val : tagval,
                display : includedActiveList ? "block" : "none"
            }, () => {})
    }

    checkCheck(tag){
        return (this.props.activeTags.includes(tag))
    }

    render(){

        return(
            <React.Fragment>
                <TagElement tagElement={this.state.key} 
                    checkEvent={(v) => this.onCheck(v)}
                    activeTags={this.props.activeTags}
                    checked={this.checkCheck(this.state.key)}
                    />
                <ul className="tag-check-box" style={{display: this.state.display}}>
                    <li>
                        { this.state.val.map( t => (typeof(t) === 'object') ? 
                            <TagTree tagTree={t} checkedTrue={this.state.check} 
                                key={Math.random()}
                                activeTags={this.props.activeTags}/> : 
                            <TagElement tagElement={t} key={Math.random()}
                                activeTags={this.props.activeTags}
                                checked={this.checkCheck(t)}
                                /> )}
                    </li>
                </ul>
            </React.Fragment>
        )
    }
}



class TagApp extends React.Component{
    state = {
        activeTags : ["Algebra", "Sequence and Series", "Types", "Arithmatic Progression", "Arithmatic Mean"]
    }

    render(){
        return(
            <div>
                <div>&nbsp;</div>
                <h4>Select Tags</h4>
                <ul className="tag-check-box">
                    <li>
                        { this.props.tagList.map( t =>  
                            <TagTree tagTree={t} key={Math.random()} 
                                activeTags={this.state.activeTags} /> 
                        )}
                    </li>
                </ul>
            </div>
        )
    }
}

export default TagApp;

 

As a result, the leaf node correctly appears as checked while the parent node does not appear to be correctly checked.

https://i.sstatic.net/yXTnk.png

Upon inspecting the HTML file, the input shows as checked:

<input class="form-check-input" type="checkbox" 
       name="Types" id="Types" value="Types" checked>

However, it does not display as default checked.

https://i.sstatic.net/cWSyL.png

Answer №1

It is recommended to use either defaultChecked, value, or checked properties, not all of them simultaneously.

import React from "react";


class TagElement extends React.Component{

    updateCheck(tag_name){
        const checked = this.props.activeTags.includes(tag_name)
        this.props.checkEvent(!checked)
    }

    checkCheck(tag){
        return (this.props.activeTags.includes(tag))
    }

    render(){
        const tag_name = this.props.tagElement;

        return(
            <div className="form-check">
                <input className="form-check-input" 
                    type="checkbox" 
                    name={tag_name}
                    id={tag_name}
                    checked={this.checkCheck(tag_name)}
                    onChange={() => this.updateCheck(tag_name)}
                    />
                <label className="form-check-label" htmlFor={this.props.text}>
                    {tag_name}
                </label>
            </div>
        )
    }
}

NOTE: I have excluded the defaultChecked and value properties in favor of using checked.

For more information, refer to this example from React

You can also view a sandbox example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic height of a fixed-positioned Div

I encountered an issue with a Fixed positioned DIV that has dynamically appended content using jQuery. Once the height of the DIV exceeds the screen size, I am unable to view the contents at the bottom of the DIV without zooming in using the browser' ...

Ensure that the text within the ng-repeat is wrapped in a span element and each

When using ng repeat in span, I encountered a word breaking into a new line. Here is the actual output: https://i.stack.imgur.com/k4c9k.png To style this, I implemented the following CSS: border: 1px solid #ECE9E6; border-radius: 3px; text- ...

How can I use JavaScript and HTML to print a canvas that is not within the print boundaries?

As someone who is new to javascript, I recently created a canvas function that allows me to successfully print. However, I am encountering an issue with printing large canvas areas. When I navigate to the further regions of the canvas and try to print, i ...

Deactivating Node.js files in vsCode for client-side JavaScript files

I'm facing a major challenge when it comes to coding with JavaScript. I have a JavaScript file that is using Node.js, which means I am unable to manipulate the DOM elements. Take this code snippet for example: var form = document.getElementsByClassNa ...

Request made to ReactJS/NodeJS API failed due to CORS restrictions

I am utilizing Axios to send requests to my NodeJS server. Below is an example of how I make the request: let url = 'http://example.com:1337/api/' let config = { headers: { 'Content-Type': 'application/json' ...

Improve navigation by integrating jQuery validation to resolve input errors seamlessly

I have been working with the jQuery validation plugin and Bootstrap. I recently added a fixed navigation bar at the top of the page using Bootstrap CSS. However, I encountered an issue where the fixed navigation was overlapping with the error message for i ...

The Mongoose model is having issues being imported into a different Component

Attempting to utilize my model for displaying and locating users in MongoDB has hit a snag. Upon importing it into profile.js and launching my app, an error is thrown: Cannot read properties of undefined (reading 'Users') https://i.stack.imgur.c ...

I am consistently encountering the error message: "Error: Unable to locate module './framer'"

I've been running into the same issue repeatedly. I'm in the process of creating a website for a barbershop and I'm attempting to integrate events into a Google calendar using the Google API. I've installed googleapis and framer, but I ...

Obtain the attribute value from an HTML option element

Here is the code snippet I am working with: <select class="form-control valid"> <option isday="False" value="2">Value 1</option> <option isday="True" value="3">Value 2</option> <option isday="True" value="4"> ...

Uncommon Two-Toned CSS Gradients

How can I create a button that matches the attached image using CSS? I know how to achieve the border-radius, but I'm struggling with the color. Any tips? I attempted something like this: .button { border-radius: 0 4px 4px 0; background-ima ...

Collecting data with Selenium as elements load [Python]

Is there a way to scrape only the newly generated items in sequence? I have a dynamic list that loads with scrolling. There are two methods I can use to scrape all generated divs: Scroll to the bottom of the list and then scrape all generated divs. Scroll ...

Implementing a custom step connector in a Material UI stepper

Is it possible to customize the connector on a Material UI stepper? Specifically, I am looking to have arrows like those shown in the image below, rather than just a single line. https://i.sstatic.net/vJD8K.png This is for Material UI version 4 + React. ...

Is it possible for a React component to accept data and create multiple iterations of components, but struggle with implementing conditionals?

Below is an illustration of the issue I am facing: This is a Functional Component that returns an ItemList which takes in a data array of objects. The renderItem property of ItemList iterates through the data and represents each element with the item. Ad ...

Stop the continuous refreshing of React components

I'm working on a React-based web page with Material-UI that features a Babylon JS 3D view. My goal is to make the web page responsive so it can adapt to different window sizes. Additionally, I want users to be able to click on a Babylon JS button (c ...

Adjust the background to scroll to the bottom of the image first and then change it to be fixed

Here is the code I have written: body{ margin:0; padding:0; line-height: 1.5em; background-image: url(http://fehlbelichtet.stefanwensing.de/wp-content/uploads/sites/6/2016/04/alte-strasse-endlos.jpg); background-repeat:no-repeat; background-attachment: ...

Creating a reusable React component that shows checkboxes by taking in an array

I'm facing difficulties in developing a shared component that can be reused in different parts of my application. This component should receive an array of names as props and display checkboxes with the corresponding names to the right of each one. Ca ...

unable to view the contents of the template using the directive

I am facing an issue with the Directive, as it is not adding an element to the Template. This directive has been included in the .html file. There are no errors being displayed in the console. directive.js: app.directive('myDirective', function ...

Transform the look of an inactive hyperlink

Can the visual style of an HTML link be modified when it is disabled? For instance, by implementing something like this: a.disabled { color:#050; } <a class="disabled" disabled="disabled" href="#">Testing</a> The code snippet above appears ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

React Js month picker problem encountered

I am currently working on implementing a month picker using the library called react-month-picker The code is functioning correctly in React: https://codesandbox.io/s/react-month-picker-forked-84rqr However, when I tried to integrate the same code into a ...