简体   繁体   中英

calling React function-based component from vanilla JavaScript DOM

I have already achieved this using Class-based component. but want the answer using Function-based component as I am trying to use React Hooks.

The core question is I want to call a react function from JavaScript DOM on an edit button click inside a datatable action column.

I have a CRUD based react component with index.js as an entry point. Inside there is a ListPage component. but there the rows are not rendering within the react render/return method. It's been rendering using JavaScipt Datatable. the datatable rows have a button to edit the record. onClick of that button I want to update the React states to show/hide Edit form.

index.js:

import React, { useState } from "react";
import ReactDOM from "react-dom";
import CardWrapper from "../../html/wrappers/Card";
import ListPage from "./ListPage";


const Organization = () => {
    const page = {
        title : "Organization List",
        action: "list"
    } 
    const [state, setState] = useState(page);

    const showEditForm = () => {
        console.log('Edit Organizatioin');

    }

    return(
        <div>
             <CardWrapper title={page.title}>
                 {page.action === 'list' && <ListPage editRecord={showEditForm} />}
             </CardWrapper>
        </div>
    )

};


const domContainer = document.getElementById("react-app");
ReactDOM.render(<Organization 
        ref={(Organization) => { window.Organization = Organization }} 
        />, domContainer);

ListPage.js:

import React, { createRef, useState } from "react";
import Config from "../../../config";
import SearchForm from "../../html/common/SearchForm";

const ListPage = (props) => {

    editRef = createRef(props.editRecord);

    return(
        <div>
            <SearchForm placeholder="keyword" 
                id="kt_datatable_search_query"
                buttonId="kt_datatable_search_submit" 
            />
            <div id="kt_datatable"></div>
        </div>
    )
}

"use strict";
// Class definition

var KTDatatableBasic = function() {
    // Private functions

    // basic demo
    var initDatatable = function() {

        var datatable = $('#kt_datatable').KTDatatable({
            // datasource definition
            data: {
                type: 'remote',
                source: {
                    read: {
                        url: 'http://localhost:8001/api/settings/organizations/',
                        method: 'GET',
                        headers: Config.headers,
                        // sample custom headers
                        // headers: {'x-my-custom-header': 'some value', 'x-test-header': 'the value'},
                        // map: function(raw) {
                        //     // sample data mapping
                        //     var dataSet = raw;
                        //     if (typeof raw.data !== 'undefined') {
                        //         dataSet = raw.data;
                        //     }
                        //     return dataSet;
                        // },
                    },
                },
                pageSize: 10,
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true,
                saveState: false    
            },

            // layout definition
            layout: {
                scroll: true,
                footer: false,
            },
            rows: {
                autoHide: false,
            },

            // column sorting
            sortable: true,

            pagination: true,

            search: {
                input: $('#kt_datatable_search_query'),
                key: 'name',
                onEnter: true
            },

            // columns definition
            columns: [{
                    field: 'id',
                    title: '#',
                    sortable: true,
                    width: 30,
                    type: 'number',
                    textAlign: 'center',
                    selector: false,
                },
                {
                    field: 'Actions',
                    title: 'Actions',
                    sortable: false,
                    overflow: 'visible',
                    autoHide: false,
                    template: function(row) {
                        return '\
                            <a href="#" data-toggle="modal" data-target="#exampleModalSizeLg" \
                                onClick="window.Organizatioin.showEditForm(event, '+row.id+')" \
                                class="btn btn-light btn-hover-primary btn-sm btn-icon mr-2" title="Edit">\
                                <i class="flaticon2-edit text-muted"></i>\
                            </a>\
                            <a href="#" class="btn btn-light btn-hover-primary btn-sm btn-icon mr-2" title="Delete" \
                                onClick="window.Organizatioin.showDeleteForm(event, '+row.id+')" /> \
                                <i class="flaticon2-rubbish-bin-delete-button text-muted"></i>\
                            </a>\
                        ';
                    },               
                },
                {
                    field: 'status',
                    title: 'Status',  
                    template: function(row) {
                        var status = {
                            'A': {
                                'title': 'Active',
                                'class': ' label-light-success',
                            },
                            'I': {
                                'title': 'In-active',
                                'class': ' label-light-danger',
                            }
                        };
                        return '<span class="label font-weight-bold label-lg ' + status[row.status].class + ' label-inline">' + status[row.status].title + '</span>';
                    }, 
                },
                {
                    field: 'org_name',
                    title: 'Organization Name',                        
                },
                {
                    field: 'org_code',
                    title: 'Organization Code',                        
                },
                {
                    field: 'email',
                    title: 'Email',                        
                },
                {
                    field: 'website',
                    title: 'Website',                        
                },
                {
                    field: 'created_by_user.name',
                    title: 'Created By',                        
                },
                {
                    field: 'created_at',
                    title: 'Created At',                        
                },
                {
                    field: 'updated_by_user.name',
                    title: 'Updated By',                        
                },                
                {
                    field: 'updated_at',
                    title: 'Updated At',                        
                }
            ],

        });

        $('#kt_datatable_search_submit').on('click', function(e){
            // console.log($('#kt_datatable_search_query').val());
            datatable.setDataSourceParam('query.name', $('#kt_datatable_search_query').val());
            $('#kt_datatable').KTDatatable("reload");
        });

        // $(document).on('keypress',function(e) {
        //     // console.log(e.key, e.code);
        //     if(e.code === 'Enter') {
        //         e.preventDefault();
        //         $('#kt_datatable_search_submit').trigger('click');
        //     }
        // });
    };

    return {
        // public functions
        init: function() {
            initDatatable();
        },
        reload: function() {
            $('#kt_datatable').KTDatatable("reload");
        }
    };
}();

jQuery(function() {
    KTDatatableBasic.init();
});


export default ListPage;

Now in the above code, I need to pass the function in the Actions column Edit button click event to call the react function.

PS: This question is related to this post: https://gist.github.com/primaryobjects/64734b8fe3f54aa637f444c95f061eed

SOLVED

In ListPage.js: below Commented with Answer changes need to be done.

import React, { useCallback, useEffect, useRef, useState } from "react";
import Config from "../../../config";
import SearchForm from "../../html/common/SearchForm";

const ListPage = (props) => {

    const [editId, setEditId] = useState('');
    
    useEffect(()=>{
        console.log('ListPage Render', editId);
        if(editId){
            props.editRecord(editId);
        }
    }, [editId]);

    return(
        <div>
            <SearchForm placeholder="keyword" 
                id="kt_datatable_search_query"
                buttonId="kt_datatable_search_submit" 
            />
            <input name="editId" type="text" onInput={(e)=>setEditId(e.target.value)} value={editId} />
            <div id="kt_datatable"></div>
        </div>
    )
}

jQuery(function() {
    KTDatatableBasic.init();

    // ====== Answer: Need to fire input event manually =====
    window.updateEditId = function(id) {
        var ev = new Event('input', { bubbles: true});
        // ev.simulated = true;
        $("input[name='editId']").val(id)[0].dispatchEvent(ev);
    }
});

"use strict";
// Class definition
...
...
... 

/** as per above **/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM