eslint-plugin-enforce-children
v1.1.0
Published
An ESLint plugin to enforce custom parent/child constraints in JSX.
Readme
eslint-plugin-enforce-children
Enforce certain parent/child constraints in JSX, defined via user config.
Install
- If you haven’t already, install ESLint:
npm install --save eslint- Install the plugin:
npm install --save eslint-plugin-enforce-childrenUsage
- Add
parent-childto your ESLint configuration. For example, if you use an .eslintrc.json file:
{
"plugins": ["enforce-children"],
"rules": {
"enforce-children/enforce-children": [
"error",
{
"rules": {
// Each key is a parent component, and the array is the list of allowed children.
"Grid": ["Row"],
"Row": ["Col"],
// etc.
}
}
]
}
}- Configure the rule: Pass an object with a rules property to define which child components are allowed under specific parents. The rule’s configuration expects a structure like this:
{
"rules": {
"Grid": ["Row"],
"Row": ["Col"],
// ...
}
}- Key: The name of the parent JSX component.
- Value: An array of allowed child JSX component names.
- Lint your code: Run ESLint, and it will report any invalid children.
Setup
- Rule Name:
enforce-children/enforce-children - Type:
problem - Description: Ensures that only specified child components appear within certain parent components.
Options
| Option | Description | Type | Required |
| -----------------| ----------------------------------------------------------------------------------------------------------------------------| -------------| -------- |
| rules | An object whose keys are parent component names and values are arrays of allowed children |Object | yes |
Examples
Valid Given a configuration:
{
"rules": {
"Grid": ["GridItem"]
}
}This is valid:
function App() {
return (
<Grid>
<Row>
<Col size={2} offset={2}>
<div style={style}>Col-2 offset-2</div>
</Col>
<Col size={6} offset={0}>
<div style={style}>Col-6 offset-0</div>
</Col>
</Row>
<Row>
<Col size={5} offset={2}>
<div style={style}>Col-5 offset-2</div>
</Col>
<Col size={3} offset={0}>
<div style={style}>Col-3 offset-0</div>
</Col>
</Row>
</Grid>
);
}Invalid With the same configuration above:
function App() {
return (
<Grid>
<Col size={3} offset={0}> {/* ❌ Only these children (Row) are allowed inside <Grid>. Found <Col>. */}
<div>Col-3 offset-0</div>
</Col>
</Grid>
);
}How It Works
- The rule checks each
JSXElementnode. - It identifies the parent component name (e.g.,
Grid). - It looks up the array of allowed children from your user-defined config (e.g.,
[ "Row"]). - It checks each JSX child to see if it is in the allowed list.
- If not, it reports an error.
License
MIT Licensed © 2025 Hamik25
