move logic out to parent component.

main
sigonasr2, Sig, Sigo 3 years ago
parent 27f921346f
commit 07e69074ec
  1. 41
      equations/src/App.js

@ -3,25 +3,46 @@ import {useEffect,useState} from 'react';
import './App.css';
function Equation(p) {
const {data} = p
const [operator,setOperator] = useState("disabled")
const [field,setField] = useState(Object.keys(data)[0])
const {data,id,equationParts,setEquationParts,field,operator} = p
return <div style={{display:"inline-block",border:"1px solid black"}}>
<select onChange={(ev)=>{setField(ev.currentTarget.value)}}>
{Object.keys(data).map((key)=><option value={key}>{key}</option>)}
function updateEquation(field,operator) {
var eq = [...equationParts]
eq[id].field=field
eq[id].operator=operator
setEquationParts(eq)
}
return <><div style={{display:"inline-block",border:"1px solid black"}}>
<select onChange={(ev)=>{
updateEquation(ev.currentTarget.value,operator)
}}>
{Object.keys(data).map((key)=><option key={key} value={key}>{key}</option>)}
</select><br/>
{data[field]}</div>
{data[field]}</div><div style={{display:"inline-block",border:"1px solid black"}}>
<select onChange={(ev)=>{updateEquation(field,ev.currentTarget.value)}}>
{["+","-","x","÷","()"].map((key)=><option key={key} value={key}>{key}</option>)}
</select><br/>{id}</div></>
}
function EquationBuilder(p) {
const {data} = p
const [equationParts,setEquationParts] = useState([<Equation data={data}/>])
const [equationParts,setEquationParts] = useState([])
const [equation,setEquation] = useState([])
useEffect(()=>{
var newEq = []
for (var i=0;i<equationParts.length;i++) {
newEq.push(data[equationParts[i].field])
newEq.push(equationParts[i].operator)
}
setEquation(newEq)
},[equationParts])
return <>
<button onClick={()=>{
setEquationParts([...equationParts,<Equation data={data}/>])}}>+</button>
setEquationParts([...equationParts,{field:Object.keys(data)[0],operator:"+"}])}}>+</button>
<br/><br/>
{equationParts.map((eq,i)=><Equation equationParts={equationParts} setEquationParts={setEquationParts} id={i} data={data} field={equationParts[i].field} operator={equationParts[i].operator}/>)}
<br/><br/>
{equationParts.map((eq)=>eq)}</>
{equation}
</>
}
function App() {

Loading…
Cancel
Save