Jump to content

JSX (JavaScript): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Tool
Tags: Reverted possible vandalism references removed Mobile edit Mobile web edit
m Reverted edit by 41.89.46.2 (talk) to last version by Sorrel
 
Line 1: Line 1:
{{Short description|JavaScript syntax extension}}
import React, { useEffect, useState, useRef } from "react";
'''JSX''' (sometimes referred to as '''JavaScript XML''') is an XML-like extension to the [[JavaScript]] language syntax.<ref name=":0">{{cite web|title=Draft: JSX Specification|url=https://facebook.github.io/jsx/|website=JSX|publisher=Facebook|access-date=7 April 2018}}</ref> Initially created by [[Meta Platforms|Facebook]] for use with [[React (JavaScript library)|React]], JSX has been adopted by multiple [[web framework]]s.<ref name=Larsen>{{cite book |last=Larsen|first=John|title=React Hooks in Action With Suspense and Concurrent Mode| year= 2021|publisher= Manning |isbn= 978-1720043997}}</ref>{{rp|5}}<ref name=Wieruch>{{cite book |last=Wieruch|first=Robin|title=The Road to React |date=14 September 2018 |publisher= Leanpub|isbn= 978-1720043997}}</ref>{{rp|11}} Being a [[syntactic sugar]], JSX is generally [[transpiler|transpiled]] into nested JavaScript function calls structurally similar to the original JSX.
import { Card, CardContent } from "@/components/ui/card";
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";

const DIGITS = [...Array(10).keys()];
const COLORS = ["#FF6384", "#FFCE56", "#4BC0C0", "#36A2EB", "#9966FF", "#FF9F40", "#C9CBCF", "#8E44AD", "#2ECC71", "#E74C3C"];

export default function TradingDashboard() {
const [ticks, setTicks] = useState([]);
const [evenCount, setEvenCount] = useState(0);
const [oddCount, setOddCount] = useState(0);
const [matchDigit, setMatchDigit] = useState(null);
const [matchTimer, setMatchTimer] = useState(30);
const [accuracy, setAccuracy] = useState({ success: 75.4, failure: 24.6 });
const [animate, setAnimate] = useState(false);
const [matchHistory, setMatchHistory] = useState([]);
const alertAudio = useRef(typeof Audio !== "undefined" ? new Audio("/alert.mp3") : null);

useEffect(() => {
const interval = setInterval(() => {
const tick = Math.floor(Math.random() * 10);
setTicks((prev) => [...prev.slice(-29), tick]);
setEvenCount((prev) => (tick % 2 === 0 ? prev + 1 : prev));
setOddCount((prev) => (tick % 2 !== 0 ? prev + 1 : prev));
}, 1000);
return () => clearInterval(interval);
}, []);

useEffect(() => {
if (!matchDigit) return;
const timer = setInterval(() => {
setMatchTimer((prev) => {
if (prev <= 1) {
setMatchDigit(null);
clearInterval(timer);
return 30;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [matchDigit]);

useEffect(() => {
if (!animate) return;
const timer = setTimeout(() => setAnimate(false), 3000);
return () => clearTimeout(timer);
}, [animate]);

const predictDigit = () => {
const frequency = Array(10).fill(0);
ticks.forEach((tick) => frequency[tick]++);
const mostFreq = frequency.indexOf(Math.max(...frequency));
const highestCount = Math.max(...frequency);
if (highestCount > 6) {
setMatchDigit(mostFreq);
setMatchTimer(30);
setAnimate(true);
setMatchHistory((prev) => [...prev.slice(-9), mostFreq]);
alertAudio.current?.play();
}
};

const frequencyData = DIGITS.map((digit) => ({
digit,
count: ticks.filter((t) => t === digit).length,
}));

const pieData = [
{ name: "Even", value: evenCount },
{ name: "Odd", value: oddCount },
];

// Custom SVG wheel for Even/Odd with labels
const total = evenCount + oddCount;
let startAngle = 0;
const slices = pieData.map((slice) => {
const sliceAngle = (slice.value / total) * 2 * Math.PI;
const x1 = Math.cos(startAngle) * 100;
const y1 = Math.sin(startAngle) * 100;
const x2 = Math.cos(startAngle + sliceAngle) * 100;
const y2 = Math.sin(startAngle + sliceAngle) * 100;
const largeArcFlag = sliceAngle > Math.PI ? 1 : 0;
const pathData = [
`M 0 0`,
`L ${x1} ${y1}`,
`A 100 100 0 ${largeArcFlag} 1 ${x2} ${y2}`,
`Z`,
].join(" ");
const midAngle = startAngle + sliceAngle / 2;
const labelX = Math.cos(midAngle) * 60;
const labelY = Math.sin(midAngle) * 60;
startAngle += sliceAngle;
return {
pathData,
color: slice.name === "Even" ? "#36A2EB" : "#E74C3C",
label: `${slice.name} (${((slice.value / total) * 100).toFixed(0)}%)`,
labelX,
labelY,
};
});

return (
<div className="bg-black text-white min-h-screen p-6 font-mono">
<h1 className="text-center text-2xl mb-4">Emphasized Automated Predictions</h1>

<div className="text-4xl flex justify-center space-x-2 mb-6">
{ticks.slice(-9).map((tick, i) => (
<span key={i} style={{ color: COLORS[tick] }}>
{tick}
</span>
))}
</div>

<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card className="bg-zinc-900">
<CardContent className="p-4">
<h2 className="text-lg mb-2">Frequency Distribution</h2>
<ResponsiveContainer width="100%" height={200}>
<BarChart data={frequencyData}>
<XAxis dataKey="digit" stroke="#ccc" />
<YAxis stroke="#ccc" />
<Tooltip />
<Bar dataKey="count" fill="#36A2EB" />
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>

<Card className="bg-zinc-900 flex flex-col justify-center items-center text-center">
<CardContent className="p-4">
<p className="text-md">Volatility 10 (1s)</p>
<p className="text-2xl mt-2">Signal Valid</p>
<p className="text-4xl mt-1" style={{ color: "#36A2EB" }}>
{matchDigit !== null ? `${matchTimer}s` : "--"}
</p>
</CardContent>
</Card>

<Card className="bg-zinc-900">
<CardContent className="p-4">
<h2 className="text-lg mb-2">Even/Odd Ratio</h2>
<ResponsiveContainer width="100%" height={200}>
<PieChart>
<Pie data={pieData} dataKey="value" innerRadius={50} outerRadius={80}>
<Cell fill="#36A2EB" />
<Cell fill="#E74C3C" />
</Pie>
</PieChart>
</ResponsiveContainer>
<div className="flex justify-around mt-2">
<p className="text-lg text-cyan-400">{evenCount}</p>
<p className="text-lg text-pink-400">{oddCount}</p>
</div>
</CardContent>
</Card>
</div>

{/* NEW: Custom Even/Odd Wheel */}
<div className="mt-10 flex justify-center">
<svg
width={220}
height={220}
viewBox="-110 -110 220 220"
role="img"
aria-label="Even and Odd distribution wheel"
>
{slices.map(({ pathData, color, label, labelX, labelY }, i) => (
<g key={i}>
<path d={pathData} fill={color} />
<text
x={labelX}
y={labelY}
fill="#fff"
fontWeight="bold"
fontSize="14"
textAnchor="middle"
dominantBaseline="middle"
>
{label}
</text>
</g>
))}
</svg>
</div>

<div className="mt-8 text-center">
<h2 className="text-xl">Matches Digit Prediction</h2>
<p className="text-3xl mt-2">
{matchDigit !== null ? (
<span className={`text-yellow-400 ${animate ? "pulse-ring p-2" : ""}`}>[{matchDigit}]</span>
) : (
<button onClick={predictDigit} className="mt-4 px-4 py-2 bg-blue-600 rounded">
Predict Matches Digit
</button>
)}
</p>

<div className="mt-6">
<h3 className="text-lg mb-2">Prediction History</h3>
<div className="flex justify-center space-x-2 text-xl">
{matchHistory.map((digit, index) => (
<span key={index} style={{ color: COLORS[digit] }}>
[{digit}]
</span>
))}
</div>
</div>
</div>

<style jsx>{`
@keyframes pulse-ring {
0% {
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.7);
}
70% {
box-shadow: 0 0 0 10px rgba(34, 197, 94, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0);
}
}
.pulse-ring {
animation: pulse-ring 1.5s infinite;
border-radius: 50%;
}
`}</style>
</div>
);
}


==Markup==
==Markup==

Latest revision as of 11:41, 29 May 2025

JSX (sometimes referred to as JavaScript XML) is an XML-like extension to the JavaScript language syntax.[1] Initially created by Facebook for use with React, JSX has been adopted by multiple web frameworks.[2]: 5 [3]: 11  Being a syntactic sugar, JSX is generally transpiled into nested JavaScript function calls structurally similar to the original JSX.

Markup

[edit]

An example of JSX code:

const App = () => {
   return (
     <div>
       <p>Header</p>
       <p>Content</p>
       <p>Footer</p>
     </div>
   ); 
}

Nested elements

[edit]

Multiple elements on the same level need to be wrapped in a single React element such as the <div> element shown above, a fragment delineated by <Fragment> or in its shorthand form <>, or returned as an array.[4][5][3]: 68–69 

Attributes

[edit]

JSX provides a range of element attributes designed to mirror those provided by HTML. Custom attributes can also be passed to the component.[6] All attributes will be received by the component as props.

JavaScript expressions

[edit]

JavaScript expressions (but not statements) can be used inside JSX with curly brackets {}:[3]: 14–16 

  <h1>{10+1}</h1>

The example above will render:

  <h1>11</h1>

Conditional expressions

[edit]

If–else statements cannot be used inside JSX but conditional expressions can be used instead. The example below will render { i === 1 ? 'true' : 'false' } as the string 'true' because i is equal to 1.

const App = () => {
   const i = 1;

   return (
     <div>
       <h1>{ i === 1 ? 'true' : 'false' }</h1>
     </div>
   );
}

The above will render:

<div>
  <h1>true</h1>
</div>

Functions and JSX can be used in conditionals:[3]: 88–90 

const App = () => {
   const sections = [1, 2, 3];

   return (
     <div>
       {sections.map((n,i) => (
           /* 'key' is used by React to keep track of list items and their changes */
           /* Each 'key' must be unique */
           <div key={"section-" + n}>
               Section {n} {i === 0 && <span>(first)</span>}
           </div>
       ))}
     </div>
   );
}

The above will render:

<div>
  <div>Section 1<span>(first)</span></div>
  <div>Section 2</div>
  <div>Section 3</div>
</div>

Code written in JSX requires conversion with a tool such as Babel before it can be understood by web browsers.[7][8]: 5  This processing is generally performed during a software build process before the application is deployed.

See also

[edit]

References

[edit]
  1. ^ "Draft: JSX Specification". JSX. Facebook. Retrieved 7 April 2018.
  2. ^ Larsen, John (2021). React Hooks in Action With Suspense and Concurrent Mode. Manning. ISBN 978-1720043997.
  3. ^ a b c d Wieruch, Robin (14 September 2018). The Road to React. Leanpub. ISBN 978-1720043997.
  4. ^ Clark, Andrew (September 26, 2017). "React v16.0§New render return types: fragments and strings". React Blog.
  5. ^ "React.Component: render". React.
  6. ^ Clark, Andrew (September 26, 2017). "React v16.0§Support for custom DOM attributes". React Blog.
  7. ^ Fischer, Ludovico (2017-09-06). React for Real: Front-End Code, Untangled. Pragmatic Bookshelf. ISBN 9781680504484.
  8. ^ Larsen, John (2021). React Hooks in Action With Suspense and Concurrent Mode. Manning. ISBN 978-1720043997.
[edit]