Reputation: 13262
I have a React Native snippet that is export default connect(mapStateToProps, mapDispatchToProps)($0)
where the cursor appears in the final parens so I can enter the class name.
Assuming I'm always using this snippet in a file that has a class defined in it (class ClassName extends Component {
), is there a way to write the snippet so that it automatically fills in the current ClassName? Using regexp or something, to start.
For example, given this code at the beginning of the file:
import React, { Component } from "react";
import { connect } from "react-redux";
class MyClass extends Component {
...
...
When I type, inside that file, my snippet shortcut for what is currently export default connect(mapStateToProps, mapDispatchToProps)($0)
(which gives me that code with the cursor where the $0
is) I want it to instantly get this:
export default connect(mapStateToProps, mapDispatchToProps)(MyClass)
Perhaps it's something like this:
"body": "export default connect(mapStateToProps, mapDispatchToProps)({/class (\w+) extends/})"```
Upvotes: 0
Views: 342
Reputation: 181359
You can't put a regular expression into a snippet except to transform one of the built-in variables. If MyClass
was already on the clipboard you could just use $CLIPBOARD
in your snippet:
"body": "export default connect(mapStateToProps, mapDispatchToProps)($CLIPBOARD)"
Update: new answer
Using an extension that I wrote, Find and Transform, this is now pretty easy. It allows you to get the entire text and do a match in the replace
to get the info you need from any part of the file - as long as you can make a regex for it.
Put this keybinding in your keybindings.json
:
{
"key": "alt+e",
"command": "findInCurrentFile",
"args": {
// no find necessary, will insert returned value at cursor(s)
"replace": [
"$${",
"const fullText = `${getDocumentText}`;",
"let foundClass = '';", // set to empty string in case of no match in text
"const match = fullText.match(/class ([^\\s]+) extends/);",
"if (match?.length) foundClass = match[1];", // get capture group 1
"return `export default connect(mapStateToProps, mapDispatchToProps)(${foundClass})`;",
"}$$"
],
"postCommands": "cancelSelection"
},
}
Upvotes: 1