I'm trying to learn react by coding, here i have come up with this code which works. but only i need to know how to use if else or maybe ternary operator here: What i want to achieve is this: when user comes to the page this is already there :
{sisalto.map(({ avain, value }, index) => (
<div>
<div>
<IndexBox y={avain} />
</div>
<div>
<ValueBox value={value} />
</div>
</div>
))}
and when user writes something on input then this comes instead of the first one:
{searchResults.map(({ avain, value }, index) => (
<div>
<div>
<IndexBox y={avain} />
</div>
<div>
<ValueBox value={value} />
</div>
</div>
))}
my code:
function App() {
const [data, setData] = useState([])
const [searchResults, setSearchResults] = useState([])
const [searchTerm, setSearchTerm] = useState('')
const [sisalto, setSisalto] = useState([])
const fetchData = () => {
let corsAnywhere = 'https://cors-anywhere.herokuapp.com/'
let something = 'http://ksngfr.com/something.txt'
fetch(corsAnywhere + something)
.then(response => response.text())
.then(result => {
const theDataArr = result.replace(/\n/g, ' ')
const f = theDataArr.split(' ')
setData(f)
})
}
useEffect(() => {
fetchData()
}, [searchTerm])
useEffect(() => {
const mappedResult = data.map(d => {
var propertyK = d.split(':')[0]
var propertyv = d.split(':')[1]
return {
avain: propertyK,
value: propertyv
}
})
setSisalto(mappedResult)
const results = mappedResult.filter(each => each.avain === searchTerm)
setSearchResults(results)
}, [data, searchTerm])
console.log(sisalto)
return (
<div>
<header>
<div>
<h1>something</h1>
<input
type="text"
value={searchTerm}
placeholder="Search..."
onChange={e => setSearchTerm(e.target.value)}
/>
</div>
</header>
<div>
{searchResults.map(({ avain, value }, index) => (
<div>
<div>
<IndexBox y={avain} />
</div>
<div>
<ValueBox value={value} />
</div>
</div>
))}
</div>
</div>
)
}
export default App
data i'm fetching:
/* ------------------------
2005-07-09 03:05
1:74539
2:29734
3:95426
4:35489
------------------------ */
You can use Ternary Operator like this
<div>
{
isTrue
? (<div>YEP</div>)
: (<div>NO</div>)
}
</div>
Now you can use React.Fragment
to achieve your goal like this -
<div>
{
isTrue
? (<React.Fragment>{/* map */}</React.Fragment>)
: (<React.Fragment>{/* map */}</React.Fragment>)
}
</div>
// React.Fragment shorthand
<div>
{
isTrue
? (<>{/* map */}</>)
: (<>{/* map */}</>)
}
</div>
If you don't want anyting in else
statement just let it be null
like this
{ isTrue ? <>YEP</> : null }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.