Was trying out nested ternary render, but the syntax doesn't seem to be valid?
export default function App() {
const toggle = true;
const toggle2 = true;
return (
<div className="App">
{toggle ? (
<div>true</div>
)
: (
{toggle2 ? (
<div>false, true</div>
): (
<div>false, false</div>
)}
)}
</div>
);
}
Single level works though:
export default function App() {
const toggle = true;
const toggle2 = true;
return (
<div className="App">
{toggle ? (
<div>true</div>
)
: (
<div>false</div>
)}
</div>
);
}
you got lost with all these parenthesis and curly braces. I don't know who started wrapping every piece of JSX in parenthesis but you don't need it and to me it's usually just noise.
export default function App() {
const toggle = true;
const toggle2 = true;
return <div className="App">
{
toggle ? <div>true</div>
: toggle2 ? <div>false, true</div>
: <div>false, false</div>
}
</div>;
}
with some parenthesis:
export default function App() {
const toggle = true;
const toggle2 = true;
return <div className="App">
{toggle ? (
<div>true</div>
) : toggle2 ? (
<div>false, true</div>
) : (
<div>false, false</div>
)}
</div>;
}
You add an extra {}. It should be :
<div className="App">
{toggle ? (
<div>true</div>
)
: (
toggle2 ? (
<div>false, true</div>
): (
<div>false, false</div>
)
)}
</div>
This should do the job:
<div className="App">
{toggle ? <div>true</div> : toggle2 ? <div>false, true</div> : <div>false, false</div>}
</div>
I personally find it easier to read when using React.Fragments, for example:
export default function App() {
const toggle = true;
const toggle2 = true;
return (
<div>
{toggle
? <div>true</div>
: (
<>
{toggle2
? <div>false, true</div>
: <div>false, false</div>
}
</>
)
}
</div>
);
}
But you can omit the second pair of braces and the React.Fragment to make it more compact:
export default function App() {
const toggle = true;
const toggle2 = true;
return (
<div>
{toggle
? <div>true</div>
: toggle2
? <div>false, true</div>
: <div>false, false</div>
}
</div>
);
}
Related
I have this :
useEffect(() => {
createRoot(document.getElementById("tarde_volume")).render(
showTotalNumberOfShares(props.instrument?.TotalNumberOfSharesTraded),
);
createRoot(document.getElementById("tarde_value")).render(
showTotalTradeValue(props.instrument?.TotalTradeValue),
);
}, []);
.
const showTotalNumberOfShares = totalNumberOfSharesValue => {
return (
<>
<ThemeProvider theme={theme}>
<Tooltip
arrow
placement="top"
title={comma(totalNumberOfSharesValue) || ""}
>
<Grid
Grid
item
className={clsx(
classes.direction,
compact ? classes.tableDigitMobile : classes.tableDigit,
)}
ref={React.createRef()}
>
{props.instrument ? (
<div id="total_number_of_shared">
{shortenNumber(totalNumberOfSharesValue)}
</div>
) : (
loading
)}
</Grid>
</Tooltip>
</ThemeProvider>
</>
);
};
I get this Warning:
Warning: You are calling ReactDOMClient.createRoot() on a container
that has already been passed to createRoot() before. Instead, call
root.render() on the existing root instead if you want to update it.
Where is my mistake?
i have this function in javascript:
export const commonRenderer = (option, useFormatter, hasSubLabel) => {
if (useFormatter && hasSubLabel) {
return (
<React.Fragment>
<FormattedMessage id={option.label} /><br /><FormattedMessage id={option.subLabel} />
</React.Fragment>
);
}
if (!useFormatter && hasSubLabel) {
return (
<React.Fragment>
{option.label}<br />{option.subLabel}
</React.Fragment>
);
}
if (useFormatter && !hasSubLabel) {
return (
<FormattedMessage id={option.label} />
);
}
return option.label;
};
and somehow i want to simplify this seems it looks really odd to me but im afraid of losing some cases. Any help?
Not sure if it's simpler or not, but you may try something like this:
export const commonRenderer = (option, useFormatter, hasSubLabel) => {
const Element = useFormatter ? FormattedMessage : React.Fragment;
const attr = useFormatter ? 'id' : 'children';
return (
<React.Fragment>
<Element {...{ [attr]: option.label }} />
{hasSubLabel && (
<React.Fragment>
<br />
<Element {...{ [attr]: option.subLabel }} />
</React.Fragment>
)}
</React.Fragment>
);
};
my state variable contains an array of objects(where is each object contains username,user_DP,imageUrl, caption) which is to be rendered but while using map() to render gives an error that I am unable to resolve.
example of state variable :
this.state = {
route: 'signin',
postDetails: [...]
};
and my render() looks like
render(){
const {route, postDetails} = this.state;
return (
<div className="App">
{
route === 'home' ?
<Navbar/>
{
postDetails.map((post,index)=>{
return(<Post
key = {index}
username = {post.username}
user_DP = {post.user_DP}
imageUrl = {post.imageUrl}
caption = {post.caption}
/>);
})
}
:
(
route === 'signin'?
<Signin onRouteChange = {this.onRouteChange}/>
:
<Signup onRouteChange = {this.onRouteChange}/>
)
}
</div>
);
}
I am getting an error like this
Syntax error: Unexpected token, expected ":" (44:13)
42 | route === 'home' ?
43 | <Navbar/>
> 44 | {
| ^
45 | postDetails.map((post,index)=>{
46 | return(<Post
47 | key = {index}
please help in removing this error it will greatly help me.
Your <Navbar /> and map() with <Post>s must be within a single node. You might use React.Fragment or wrap them in a <div> if that doesn't break your design:
The React.Fragment component lets you return multiple elements in a render() method without creating an additional DOM element.
function render() {
const { route, postDetails } = this.state;
return (
<div className="App">
{route === "home" ? (
<> {/* <- shorthand for <React.Fragment> */}
<Navbar />
{postDetails.map((post, index) => {
return (
<Post
key={index}
username={post.username}
user_DP={post.user_DP}
imageUrl={post.imageUrl}
caption={post.caption}
/>
);
})}
</> {/* <- shorthand for </React.Fragment> */}
) : route === "signin" ? (
<Signin onRouteChange={this.onRouteChange} />
) : (
<Signup onRouteChange={this.onRouteChange} />
)}
</div>
);
}
When I write this code I have an error:
React Hook "useRef" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
What should I do with this code?
return ITEMS.map((item, i) => {
const elementRef = useRef(null);
return (
<div
ref={elementRef}
key={i}
>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item
parentRef={elementRef}
/>
)}
</Wrapper>
</div>
);
}
Here are two possibilities, Either using useRef with an object/array, or using createRef as suggested by Yevgen Gorbunkov.
I'm not entirely sure as to the viability of these as the createRef option will create entirely new refs on each render, and the useRef option you'll need to make sure your keys/indexes are always the same.
const ITEMS = [{ name: "test" }, { name: "test2" }];
export default function App() {
const ref = useRef({});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{ITEMS.map((item, idx) => {
return (
<div key={idx} ref={element => (ref.current[idx] = element)}>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item parentRef={ref.current[idx]} />
)}
</Wrapper>
</div>
);
})}
{ITEMS.map((item, idx) => {
const ref = createRef();
return (
<div key={idx} ref={ref}>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && <Item parentRef={ref} />}
</Wrapper>
</div>
);
})}
</div>
);
}
<div class='row m-b-0'>
<div class="col-sm-6 col-md-4">...</div>
<div class="col-sm-6 col-md-4">...</div>
<div class="col-sm-6 col-md-4">...</div>
</div>
I am used to using jQuery when I implement like jQuery inside reactjs but in react can not render.
Below is my code.
How can I solve it?
render(){
let tag1 = '';
let tag2 = '';
const wrapper = (value,i) => {
if(i === 1 || i === 4 || i === 7 || i === 10 || i === 13){
tag1 = "<div class='row m-b-0'>";
} else {
tag1 = '';
}
if(i === 3 || i === 6 || i === 9 || i === 12 || i === 15){
tag2 = "</div>";
} else {
tag2 = '';
}
return (<Content data={i} value={value} tag1={tag1} tag2={tag2} />)
}
return(
<Fragment>
{
this.state.data.map((value,i) =>
wrapper(value,i)
)
}
</Fragment>
)
}
}
const Content = (props) => {
return(
<Fragment key={props.data}>
{
props.tag1
}
...
{
props.tag2
}
</Fragment>
)
}
It's possible to render 'raw html' in react (f.e. dangerouslySetInnerHTML or fragments) but using react to glue strings/html partials is a bad practice.
React creates (virtual) nodes (fragment) with restrictions - I'm affraid it can't contain tag opening and closing in another node.
You have to structure components closer to required html. In this case (you didn't show data structure) I would divide data in 3-elements sets returning complete ('row') structure/fragment in one step:
return (
<div class='row m-b-0' key={i}>
<div class="col-sm-6 col-md-4">{subset[0]}/div>
<div class="col-sm-6 col-md-4">{subset[1]}/div>
<div class="col-sm-6 col-md-4">{subset[2]}/div>
</div>
)
Then you can refactor further:
return (
<div class='row m-b-0' key={i}>
{subset.map((value,i) => (
<div class="col-sm-6 col-md-4" key={i}>{value}</div>
)}
</div>
)
and later
return (
<div class='row m-b-0' key={i}>
{subset.map((value,i) => renderCell(value,i) )}
/div>
)
and probably making Cell component
return (
<Row ...props.rowProps key={i}>
{subset.map((value,i) => <Cell value={value} i={i} ...props.cellProps/> )}
</Row>
)
or if you need simple conditional depth
if(!!props.someCond) return (
<Row ...props.rowProps key={i}>
{subset.map((value,i) => <Cell value={value} i={i} ...props.cellProps/> )}
</Row>
}
return (
<Fragment key={i}>
{subset.map((value,i) => <Cell value={value} i={i} ...props.cellProps/> )}
</Fragment>
}
or in JSX, sth like:
return (
{!!props.someCond ?
<Row ...props.rowProps key={i}>
: <Fragment key={i}>}
{subset.map((value,i) => <Cell value={value} i={i} ...props.cellProps/> )}
{!!props.someCond ? </Row> : </Fragment> }
)
from some time you can return more than one node and sth like this should work:
return (
{!!props.someCond && <Row ...props.rowProps key={i}>}
{subset.map((value,i) => <Cell value={value} i={i} ...props.cellProps/> )}
{!!props.someCond && </Row> }
)
There are many possibilities but you have to 'think in react', more structured way ;)
PS. use modulo operator to simplify condition
const openingTag = (i>0 && (i % 3 === 1)); // 1,4,7...
const tag1 = openingTag ? `<div class='row m-b-0'>` : null; // null renders nothing in react
having prepared boolean value in jsx you can:
{openingTag && <div class='row m-b-0'>}
but probably it won't work without closing - use it for entire components or (structured) blocks.