reflex icon indicating copy to clipboard operation
reflex copied to clipboard

Enhance Pynecone with Custom React Hooks

Open karndeb opened this issue 2 years ago β€’ 2 comments

Hi team, I am trying to compile a mui data table js script. My custom mui data table script is `

  class CustomTag(pc.Component):
  
      library = '@mui/material/styles'
  
      tag = 'ThemeProvider'
  
      # style: pc.Var[Dict]
  
      def _get_imports(self):
          return pc.utils.merge_imports(
              super()._get_imports(), {"@mui/material/styles": {"createTheme"}, })
  
      def _get_custom_code(self) -> Optional[str]:
          return """ const theme = createTheme({
                  components: {
                      MUIDataTableBodyCell: {
                          styleOverrides:{
                              root: {
                                  backgroundColor: "#FFFFFF"
                              }
                          }
                      }
                  }
               })
          """
  
      def get_custom_code(self) -> Set[str]:
          # Store the code in a set to avoid duplicates.
          code = set()
  
          # Add the custom code for this component.
          custom_code = self._get_custom_code()
          if custom_code is not None:
              code.add(custom_code)
  
          return code
  
      @classmethod
      def create(
              cls, *children, data=None, columns=None, options=None, **props
      ) -> pc.Component:
          """Create a custom tag component.
          """
          if len(children) == 0:
              children = []
              if data:
                  children.append(MUIDataTables.create(data=data, columns=columns, options=options))
  
          return super().create(*children, **props)
  
  
  class MUIDataTables(pc.Component):
      """A component that wraps ag grid component."""
  
      library = "mui-datatables"
  
      tag = "MUIDataTable"
  
      data: pc.Var[List[List]]
  
      columns: pc.Var[List]
  
      options: pc.Var[Dict]
  
      # def render(self):
      #     Imports = self.get_imports()
  
  
  mui_dt = CustomTag.create
  
  columns = ["Name", "Title", "Location"]
  
  data = [["Gabby George", "Business Analyst", "Minneapolis"],
      [
        "Aiden Lloyd",
        "Business Consultant for an International Company and CEO of Tony's Burger Palace",
        "Dallas"
      ],
      ["Jaden Collins", "Attorney", "Santa Ana"],
      ["Franky Rees", "Business Analyst", "St. Petersburg"],
      ["Aaren Rose", None, "Toledo"],
      ["Johnny Jones", "Business Analyst", "St. Petersburg"],
      ["Jimmy Johns", "Business Analyst", "Baltimore"],
      ["Jack Jackson", "Business Analyst", "El Paso"],
      ["Joe Jones", "Computer Programmer", "El Paso"],
      ["Jacky Jackson", "Business Consultant", "Baltimore"],
      ["Jo Jo", "Software Developer", "Washington DC"],
      ["Donna Marie", "Business Manager", "Annapolis"]]
  
  options = {'filter': True, 'filterType': 'dropdown', 'responsive': 'vertical',
                             'tableBodyHeight': '600px'}
  
  
  # style = {'components': {'MUIDataTableBodyCell': {'styleOverrides': {'root': {'backgroundColor': "#FFFFFF"}}}}}
  
  
  class State(pc.State):
      """The app state."""
      pass
  
  
  def index():
      return pc.center(pc.box(mui_dt(columns=columns, data=data,
                              options=options)),
                       width='1900px',
                       height='900px')
  
  # Add state and page to the app.
  
  
  app = pc.App(state=State)
  app.add_page(index)
  app.compile()

` My compiled js code that I want is

`

  import {useEffect, useRef, useState} from "react"
  
  import {useRouter} from "next/router"
  
  import {E, connect, updateState} from "/utils/state"
  
  import "focus-visible/dist/focus-visible"
  
  import {Box, Center, useColorMode} from "@chakra-ui/react"
  
  import {ThemeProvider, createTheme} from "@mui/material/styles"
  
  import MUIDataTable from "mui-datatables"
  
  import NextHead from "next/head"
  
   const theme = createTheme({
                  components: {
                      MUIDataTableBodyCell: {
                          styleOverrides:{
                              root: {
                                  backgroundColor: "#FFFFFF"
                              }
                          }
                      }
                  }
               })
          
  
  const EVENT = "ws://localhost:8000/event"
  
  export default function Component() {
  
  const [state, setState] = useState({"events": [{"name": "state.hydrate"}]})
  
  const [result, setResult] = useState({"state": null, "events": [], "processing": false})
  
  const router = useRouter()
  
  const socket = useRef(null)
  
  const { isReady } = router;
  
  const { colorMode, toggleColorMode } = useColorMode()
  
  const Event = events => setState({
  
    ...state,
  
    events: [...state.events, ...events],
  
  })
  
  useEffect(() => {
  
    if(!isReady) {
  
      return;
  
    }
  
    const reconnectSocket = () => {
  
      socket.current.reconnect()
  
    }
  
    if (typeof socket.current !== 'undefined') {
  
      if (!socket.current) {
  
        window.addEventListener('focus', reconnectSocket)
  
        connect(socket, state, setState, result, setResult, router, EVENT)
  
      }
  
    }
  
    const update = async () => {
  
      if (result.state != null) {
  
        setState({
  
          ...result.state,
  
          events: [...state.events, ...result.events],
  
        })
  
        setResult({
  
          state: null,
  
          events: [],
  
          processing: false,
  
        })
  
      }
  
      await updateState(state, setState, result, setResult, router, socket.current)
  
    }
  
    update()
  
  })
  
  return (
  
  <Center sx={{"width": "1900px", "height": "900px"}}><Box><ThemeProvider theme={theme}><MUIDataTable columns={["Name", "Title", "Location"]}
  
  options={{"filter": true, "filterType": "dropdown", "responsive": "vertical", "tableBodyHeight": "600px"}}
  
  data={[["Gabby George", "Business Analyst", "Minneapolis"], ["Aiden Lloyd", "Business Consultant for an International Company and CEO of Tony's Burger Palace", "Dallas"], ["Jaden Collins", "Attorney", "Santa Ana"], ["Franky Rees", "Business Analyst", "St. Petersburg"], ["Aaren Rose", null, "Toledo"], ["Johnny Jones", "Business Analyst", "St. Petersburg"], ["Jimmy Johns", "Business Analyst", "Baltimore"], ["Jack Jackson", "Business Analyst", "El Paso"], ["Joe Jones", "Computer Programmer", "El Paso"], ["Jacky Jackson", "Business Consultant", "Baltimore"], ["Jo Jo", "Software Developer", "Washington DC"], ["Donna Marie", "Business Manager", "Annapolis"]]}/></ThemeProvider></Box>
  
  <NextHead><title>{`Pynecone App`}</title>
  
  <meta name="description"
  
  content="A Pynecone app."/>
  
  <meta content="favicon.ico"
  
  property="og:image"/></NextHead></Center>
  
  )
  
  }

`

The problem to get this table working in pynecone is that there is no way to add the create theme hook in the component. Am I missing something here? Need some help on this. If not, do we have adding custom hooks in the roadmap. This will exponentially increase pynecone's extendibility and community driven add-ons and plugins.

karndeb avatar Feb 15 '23 12:02 karndeb

This might be duplicate to #55.

Lendemor avatar Feb 15 '23 18:02 Lendemor

Yeah it's a duplicate, but I think we will have time to add this feature soon. We have been focusing on fixing the core but will now have more time to start implementing features like this. Thanks for bringing this up

Alek99 avatar Feb 16 '23 08:02 Alek99

This was added in #810

picklelo avatar Jun 15 '23 19:06 picklelo