A bare-bones react component to build function expressions with your data.
- Typeahead support
- Full keyboard navigation and deletion
- Easy custom styling as per input
- Input validation at granular level
- Customizable options
- Single Dependency, no bloat
Install the package -
npm i react-expression-builder
OR
yarn add react-expression-builder
import ExpressionBuilder from 'react-expression-builder'
//1. accumulate your options
// fn must have an additional property 'params' - eg `params: ['dim', 'delimiter', 'occurrence_number']`
const options = [{..., key: '...', type: '...', label: '...',...}, {...}]
// regex to match entires within ""
const stringRegex = /"([^\\"]|\\")*"/
// Optional - Function called on every state change, store your changes on the server
const onChangeFn = editorState => console.log(editorState, editorState.buildExpression())
// Optional - class for the expression element, use for optional styling
const expressionRootClass = 'root-class'
// Optional - class for the input container
const expressionInputClass = 'input-class'
// Optional - Function which validates all the input values and returns a bool.
const validationFn = val => {
return !isNaN(val) || stringRegex.test(val)
}
<ExpressionBuilder
onChangeFn={onChangeFn}
options={options}
expressionRootClass={expressionRootClass} // Optional
expressionInputClass={expressionInputClass} // Optional
placeholder="Enter your expression" // Optional
initialFocus={true} // if you want your input to be focussed on mount by default
validationFn={validationFn} // Optional
/>
Uses an N-Ary tree to store/manipulate the expression data, simple recursive function gives you the complete string. You can check DataStructure.ts for the simple implementation, if curious.
Note - This only gives the skeleton and functionality, styling is upto the user, you can either make use of respective classes or wrap this component in a CSS-in-JS solution. For example, a nicely styled solution would look somewhat like this. This is not complete yet, need more work. Meanwhile, suggestions are appreciated.
Found a bug, please create an issue
© Anshuman Verma