0.0.3 • Published 2 years ago

@solidk-tech/react-class-to-jsx v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

React Class To Form

This is a helper library used to make it easier to render components on you project.

Example of usage with multiples fields.

// .src/classes/MyModel.ts
class MyModel extends MySchema{
  email: string | null = ''
  password: string | null = ''
}
// .src/schema/MySchema.ts
class MySchema extends Schema {
  translateFrom = (fieldName: string) => fieldName.toLocaleUpperCase()

  readonly fieldSet: FieldSet<MyModel> = {
    email: (schema): FieldComponent<MyModel, InputEmailProps> => ({
        component: 'input',
        props: {
          id: 'id-email',
          name: 'name-email',
          type: 'text',
          placeholder: 'This is an input',
          className: 'my-component-class',
          onChange: (event: any) => (schema.model.email = event?.target.value),
        },
      }),
      password: (schema): FieldComponent<MyModel, InputPasswordProps> => ({
        component: 'input',
        props: {
          id: 'id-password',
          name: 'name-password',
          type: 'password',
          className: 'my-component-class',
          onChange: (event: any) => (schema.model.password = event?.target.value),
        },
      }),
    }  
  }
}
// .src/App.ts
import React from 'react'
const App = () => {
  const model = new MyModel()
  return (
  <>
    {model.allFields.map((field, index) => {
      return <RenderSchema key={index} value={model} field={field} />
    })}
    <button onClick={() => console.log(model)}>Send</button>
  </>  
  )
}

Alternative you can render only a specific field of the class.

// .src/App.ts
import React from 'react'
const App = () => {
  const model = new MyModel()
  return (
  <>
    <RenderSchema value={model} field='email' />
    <RenderSchema value={model} field='password' />
  </>  
  )
}

This is how the component is gone look like:

<!-- index.html Rendered -->
<div id="root">
  <input id="id-email" name="name-email" type="text" placeholder="This is an input" class="my-component-class" value="">
  <input id="id-password" name="name-password" type="password" class="my-component-class" value="">
  <button>Send</button>
</div>