Laravel + React: Pass Function in JSON response

Viewed 214

I'm trying to generate JSON for display clickable Konva object. All attributes working as expected except onClick.

How to pass a JS function in JSON with Laravel Respons::json()?

Here's what I've tried.

return Response::json([
            'status' => 'completed',
            'message' => 'Question ID:'.$id.' Retreived',
            'data' => [
                
                    "attrs" => [
                        "width" => 1200,
                        "height"=> 200
                    ],
                    "className" => "Stage",
                    "children" => [
                        [
                            "attrs"=>[],
                            "className"=>"Layer",
                            "children"=>[
                                [
                                    "attrs"=>[
                                        "x"=>125,
                                        "y"=>100,
                                        "text"=>"Test Text",
                                        "onClick"=> "{() => console.log(test)}",
                                        "fontSize"=>25,
                                    ],
                                    "className"=>"Text"
                                ]
                            ]
                        ],
                    ]
                
            ]
        ], 200);

but I got this error

TypeError: selfListeners[i].handler.call is not a function. (In 'selfListeners[i].handler.call(this, evt)', 'selfListeners[i].handler.call' is undefined)

1 Answers

Konva is not using JSON data to attach events. JSON is used only for attributes. So such onClick event will be not attached. It will be just added as onClick attribute, which is not what you want.

And in general, I am not sure if it is a good idea to save/load events and js function inside JSON object. JSON should be used just for attributes and state of your application.

Related