Square with color based on hex color

Hello, I have JS color picker through the hooks based on tutorial from ElixirCast.
I am returning the hex-color, but I also want to return square with color based on this hex color.
Something like that:
Screenshot 2022-08-26 at 21.48.05

How can I do this please. I am a beginner.
Thank you very much for any help. :slight_smile:

Do you have some code that we can look at?

<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500"><%= site_config.color %></td>

For example here site_config.color represent hex-color. Now I need add square before <%= site_config.color %> and value in square will be site_config.color → color in hex format. This is maybe html problem more than elixir, so sorry.

Update…
Now I have this code and I manually add blue color:

<%= for site_config <- @site_configs do %>
  <tr id={"site_config-#{site_config.id}"}>
   <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
    <div class= "box" style="background-color:blue">
     <%= site_config.color %>
    </div>
   </td>

Screenshot 2022-08-27 at 0.08.25

And I want do something like that:

<%= for site_config <- @site_configs do %>
 <tr id={"site_config-#{site_config.id}"}>
  <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
   <div class= "box" style="background-color:#{site_config.color}">
    <%= site_config.color %>
   </div>
  </td>

Since style will be using a variable, it should be wrapped in {}s

2 Likes

Thanks a lot! This is probably the problem.
Now I have

<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500 ">
 <div class= " space-x-1 pl-5 box" {style="background-color:#{site_config.color}"}>
  <%= site_config.color %>
 </div>
</td>

And I see this error, but I think this is the right way! :slight_smile:

not the entire style tag, look at how it is in <tr id={"site_config-#{site_config.id}"}>

1 Like

The answer by Thomas is correct, but since you are using Tailwind, you do not need the separate style tag. You can use class={"w-8 h-8 bg-[#{site_config.color}]"} for example. Tailwind allows you to deviate from the predefined classes using the -[] syntax. Just make sure the “color” is in the correct syntax; bg-[#cccccc], your variable then needs to hold #cccccc,

1 Like

Thanks a lot guys for your help and your time. :slight_smile: I appreciate it!

That would be bad, the [] syntax only works with the JIT and tailwind wouldn’t be able to parse it correctly because the value would only be known at runtime.

1 Like

OMG, you are absolutely right. Thanks for coming back to this.

So finally I have this solution.

assets/css/app.css

.box {
   height: 20px;
   width: 20px;
   border-radius: 5px
 }

html.heex

<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500 ">
 <div class= "pl-5 box" style={"background-color:#{site_config.color}"}>
  <%= site_config.color %>
 </div>
</td>

Screenshot 2022-08-27 at 11.22.13

3 Likes