Jack Keller

#BLACKLIVESMATTER

As a human being, and developer, I stand with the Black Lives Matter Movement and you should too.

React Component Boilerplate

Shell scripting a component boilerplate for quick use!

 

In a recent project we settled on how we decided to have our React components live in their own folders, so I aimed to write a quick script that could easily create the structure and files, and even create a throwaway Jest test that passed.

Here’s what I came up with, feel free to take and modify for your own needs.

#!/bin/shgreen='\033[0;32m'
magenta='\033[0;35m'alias Reset="tput sgr0"
​
cecho() {
  echo "${2}${1}"
  Reset # Reset to normal.
  return
}CONTINUE=false
​
cecho "What do you want to name your component?" $green
read component
echo ""
cecho "What directory should $component live? (relative to src/)" $green
read directory
echo ""mkdir -p src/$directory/$component
cd src/$directory/$component# Make PasCal case dasherized for sass
dasherizedcomponent=$(echo $component \
     | sed 's/\(.\)\([A-Z]\)/\1-\2/g' \
     | tr '[:upper:]' '[:lower:]')echo "@import '/styles/scss/variables';
// Make $component Excellent!
.$dasherizedcomponent {
  // Block thing for .$dasherizedcomponent
  &-element {
    // Element things for .$dasherizedcomponent
  }
}" >> ${component}.scss;echo "import React, { useState } from 'react';
import './$component.scss';
​
const $component = ({text}) => {
  const [count, setCount] = useState(0);
​
  return (
    <div className='$dasherizedcomponent'>
      {text}
    </div>
  )
}
​
export default $component;" >> ${component}.js;# Creating File For Testing
echo "import React from 'react';
import { fireEvent, render, wait } from '@testing-library/react';
import $component from './$component';
​
const setup = (customProps ={}) => {
  const defaultProps = {};
  const props = { ...defaultProps, ...customProps};
  return render(<$component {...props}/>);
};
​
beforeEach(() => {
  jest.resetAllMocks();
});
​
describe('$component', () => {
​
  it('should render the text $component in the document', () => {
    const { getByText } = setup({ text: '$component' });
    expect(getByText('$component')).toBeInTheDocument();
  });
​
});
" >> ${component}.test.js;
​
cecho "===================================" $magenta
echo  ""
cecho "Successfully created $component!" $magenta
echo  ""

As I stated before, this assumes you want a component, test, and scss file to live in it’s own directory, and also that you’d be using BEM for structuring your CSS classes.

I dropped the script (I named it create.sh into the project root, then I added "create": "./create.sh" to the package.json scripts section so I could run npm run create from the command line, one could easily use yarn here too.

Enjoy!