Uma postagem especial, neste dia de Natal

24/12/2024

Código para a montagem de uma árvore de Natal em javascript. Id: 31

Capa do artigo Uma postagem especial, neste dia de Natal

Tutorial: Building a Static Christmas Tree Component in React

This tutorial guides you through creating a static React component that renders a Christmas tree with flashing colored lights, suitable for integration into a larger application during deployment. The component is based on the example shown in this YouTube Shorts video. We'll present the original code, explain how it works, and provide steps to build a similar component.

Original Code

Below is the complete code for the ChristmasTree component:

import { useEffect, useState } from "react";
const ChristmasTree: React.FC = () => {
// Function to get a random color
const getRandomColor = () => {
const colors = ['green', 'orange', 'cyan', 'lime', 'yellow', 'red', 'blue', 'white'];
return colors[Math.floor(Math.random() * colors.length)];
};
const [lightsOn, setLightsOn] = useState(true);
useEffect(() => {
const interval = setInterval(() => {
setLightsOn((prev) => !prev);
}, 500); // Toggle lights every 500ms
return () => clearInterval(interval);
}, []);
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
marginTop: "20px",
backgroundColor: "black",
padding: "20px"
}}
>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
backgroundColor: "black",
}}
>
{Array.from({ length: 10 }, (_, level) => (
<div
key={level}
style={{
display: "flex",
justifyContent: "center",
marginBottom: "5px",
}}
>
{Array.from({ length: level * 2 + 1 }, (_, idx) => (
<div
key={idx}
style={{
width: "20px",
height: "20px",
borderRadius: "50%",
margin: "2px",
backgroundColor: getRandomColor(),
transition: "opacity 0.4s ease-in-out",
opacity: lightsOn ? 1 : 0.7,
}}
></div>
))}
</div>
))}
</div>
<div
style={{
width: "40px",
height: "50px",
backgroundColor: "rgba(84, 7, 7, 0.929)",
marginTop: "1px",
borderRadius: "5px",
}}
></div>
</div>
);
};
export default ChristmasTree;

Video Demonstration

See the component in action: YouTube Shorts Video

How to Implement a Similar Component

To create a similar Christmas tree component and integrate it in React application, follow these steps:

Step 1: Set Up Your React Project

Ensure you have a React project set up. If not, create one using:

npx create-react-app my-app
cd my-app
npm start

This sets up a basic React environment. The component uses React hooks, so no additional dependencies are needed.

Step 2: Create the Component

Create a new file, e.g., ChristmasTree.tsx, in your project's src directory. Copy the code from the CodeBlock above into this file. The component:

  • Uses useState to manage the lightsOn state for toggling light opacity.
  • Uses useEffect to set up an interval that toggles lightsOn every 500ms.
  • Renders a tree with 10 rows of circular divs (lights) in a triangular pattern (1, 3, 5, ..., 19 lights per row).
  • Assigns random colors to each light using the getRandomColor function.
  • Includes a brown trunk at the bottom.

Step 3: Customize the Component

To create a similar component, you can modify:

  • Tree Size: Change the length: 10 in Array.from to adjust the number of rows.
  • Light Size and Spacing: Adjust the width, height, and margin in the light div's style.
  • Colors: Modify the colors array in getRandomColor to include different colors.
  • Animation Speed: Change the 500 in setInterval to adjust the flashing speed.
  • Opacity: Modify the opacity values (e.g., 1 and 0.7) for different effects.

For example, to create a smaller tree with different colors:

const getRandomColor = () => {
const colors = ['purple', 'pink', 'gold', 'silver'];
return colors[Math.floor(Math.random() * colors.length)];
};
// In the return statement
{Array.from({ length: 5 }, (_, level) => (
<div key={level} style={{ display: "flex", justifyContent: "center", marginBottom: "3px" }}>
{Array.from({ length: level * 2 + 1 }, (_, idx) => (
<div
key={idx}
style={{
width: "15px",
height: "15px",
borderRadius: "50%",
margin: "1px",
backgroundColor: getRandomColor(),
transition: "opacity 0.3s ease-in-out",
opacity: lightsOn ? 1 : 0.5,
}}
></div>
))}
</div>
))}

Step 4: Integrate into Your Application

To use the component in your application, import and include it in your main app or another component. For example:

import ChristmasTree from './ChristmasTree';
function App() {
return (
<div>
<h2>My Application</h2>
<ChristmasTree />
</div>
);
}
export default App;

Ensure the component is part of your build process for static rendering. If using a static site generator like Next.js, place it in the pages or components directory and include it in your static export configuration.

How It Works

The ChristmasTree component creates a Christmas tree-like structure using:

  • React Hooks: useState manages the lightsOn state to toggle light opacity, and useEffect sets up an interval for the flashing effect.
  • Random Colors: The getRandomColor function assigns random colors from a predefined array to each light.
  • Dynamic Rendering: Nested Array.from loops create a triangular pattern of circular divs (lights), with each row having an increasing number of lights (1, 3, 5, ..., 19).
  • Styling: Inline CSS styles create a black background, centered layout, and a brown trunk. The lights are 20x20px circles with a smooth opacity transition.
  • Animation: The lights toggle between full and reduced opacity every 500ms, creating a flashing effect.

This component is a fun way to combine React's dynamic capabilities with CSS styling to create a festive visual effect. Integrate it into your application to add a touch of holiday cheer!

Para comentários:

Se quiser comentar, sugerir (acréscimos, retificações etc), criticar, elogiar, informar, sobre algum trecho deste artigo, peço a gentileza de utilizar a área de comentários do abaixo informada, no Youtube.

Já existe uma mensagem por lá dedicada a comentários sobre temas publicados neste portal.

Essa também é uma forma de contribuir com o trabalho e estimular sua continuidade e aprimoramento.

Peço a gentileza de comentar, curtir e compartilhar o conteúdo, além de se inscrever no canal do Youtube e ativar o sino de notificações para receber notícias de novos conteúdos.

Agradeço desde já!

Destinado para esses comentários em geral:

https://www.youtube.com/@roberto_csantos/community