Roblox / roact

A view management library for Roblox Lua similar to React
https://roblox.github.io/roact
Apache License 2.0
556 stars 142 forks source link

Functional components #316

Open TheEpicFace007 opened 2 years ago

TheEpicFace007 commented 2 years ago

How can I do functional components with roact?

Is there a such thing such a useState and useEffect?

Here is how I think I should do it:

---@type Roact
local Roact = getrenv().require(game:GetService("CorePackages")["Packages"]["_Index"]["roblox_roact"]["roact"])
---@type Roact
local React = Roact

local function Button(props)
  local count = Roact.useState(value)
  return React.createElement("TextButton", {
    Text = ("Click count: %d"):format(count.value),
    [Roact.Event.MouseButton1Click] = function ()
      count.setState(count +  1)

    end
  })
end

local function App()
  return Roact.createElement("Frame", {
    Size = UDim2.fromScale(0.3, 0.4),
    AnchorPoint = Vector2.new(0, 1),
    Position = UDim2.fromScale(0.1, 0.9),
  }, {
    React.createElement("TextLabel", {
      Text = "Bible Bot",
      AnchorPoint = Vector2.new(0, 0),
      Position = UDim2.fromScale(0.5, 0.05),
      TextSize = 15
    }),
    Button({})
  })
end

Roact.unmount(getgenv().app)
getgenv().app = Roact.mount(Roact.createElement("ScreenGui", {}, App()), game.CoreGui)
SheepWizard commented 2 years ago

Someone has started working on a roact hooks library here: https://github.com/Kampfkarren/roact-hooks idk if anyone is planning on adding it to the roact library