Uma postagem especial, neste dia de Natal
24/12/2024
Código para a montagem de uma árvore de Natal em javascript. Id: 31

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 colorconst 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 500msreturn () => clearInterval(interval);}, []);return (<divstyle={{display: "flex",flexDirection: "column",alignItems: "center",marginTop: "20px",backgroundColor: "black",padding: "20px"}}><divstyle={{display: "flex",flexDirection: "column",alignItems: "center",backgroundColor: "black",}}>{Array.from({ length: 10 }, (_, level) => (<divkey={level}style={{display: "flex",justifyContent: "center",marginBottom: "5px",}}>{Array.from({ length: level * 2 + 1 }, (_, idx) => (<divkey={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><divstyle={{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-appcd my-appnpm 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 thelightsOn
state for toggling light opacity. - Uses
useEffect
to set up an interval that toggleslightsOn
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
inArray.from
to adjust the number of rows. - Light Size and Spacing: Adjust the
width
,height
, andmargin
in the light div's style. - Colors: Modify the
colors
array ingetRandomColor
to include different colors. - Animation Speed: Change the
500
insetInterval
to adjust the flashing speed. - Opacity: Modify the
opacity
values (e.g.,1
and0.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) => (<divkey={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 thelightsOn
state to toggle light opacity, anduseEffect
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!