How to render jsx in react with condition true and array mapping? - javascript

I want to render a JSX with some condition being true and map through an array.
below is the code,
{this.props.variables &&
this.props.variable.map((variable, index) => {
let element;
if (variable.anchor) {
element = document.querySelector(variable.anchor);
}
this.box_ref.current && element && (// error here
<Childcomponent
element1={this.box_ref.current}
anchor={variable.anchor}
/>)
}
}
)
}
There is an error saying that the expression is not an assignment or a call. how can I fix it? thanks.

You need to provide a return value for #Array.map callback.
Also, you should provide unique keys to React elements within an array:
<>
{this.props.variables &&
this.props.variable.map((variable, index) => {
let element;
if (variable.anchor) {
element = document.querySelector(variable.anchor);
}
// v Add return statement
return (
this.box_ref.current &&
element && (
<Childcomponent
key={index}
element1={this.box_ref.current}
anchor={variable.anchor}
/>
)
);
})}
</>

Related

How to alphabetically list an already mapped array in javascript?

Having some issues on this, my code is supposed to hit an API, return a list of counties in a state, and display them. It does display just fine, however I want them to be in alphabetical order. Because this is a react component, I cannot understand where I would do a sort function, here is the part of the function that is mapped :
{error ? (
<h1>{error.message}</h1>
) : (
counties.map(function (county, index) {
if (
county.location.split(", ")[1] === stateName &&
county.location.split(" ")[0] !== "Unassigned" &&
county.location.split(" ")[0] !== "Out"
) {
return (
<div className="card" key={index}>
<h3>{county.location.split(",")[0]}</h3>
<p>confirmed: {county.confirmed}</p>
<p>dead: {county.dead}</p>
</div>
);
} else {
return null;
}
})
)}
</div>```
Sort right before mapping. Using this you might have duplicate code. What you can do instead is 1) map the fix the way you are handling the response, 2) sort using your own sorting function, since county seems to be JSON, and 3) Finally, map your stuff and return the JSX (the only thing that is rendered is the final return)
{error ? (
<h1>{error.message}</h1>
) : (
counties.sort(/* Sort function goes here */).map(function (county, index) {
if (
county.location.split(", ")[1] === stateName &&
county.location.split(" ")[0] !== "Unassigned" &&
county.location.split(" ")[0] !== "Out"
) {
return (
<div className="card" key={index}>
<h3>{county.location.split(",")[0]}</h3>
<p>confirmed: {county.confirmed}</p>
<p>dead: {county.dead}</p>
</div>
);
} else {
return null;
}
})
)}
</div>
Maybe this will help you.
Universal sorting function:
const sortDataByProperty = (data, property) => {
const sorted = [...data].sort((a, b) => {
return a[property].toLowerCase().localeCompare(b[property].toLowerCase());
});
return sorted;
};
Your Reactjs code:
{error ? (
<h1>{error.message}</h1>
) : (
// first parameter is data object
// second is object property by which you want to sort the data
const sortedData = sortDataByProperty(counties, 'name');
sortedData.map(function (county, index) {
if (
county.location.split(", ")[1] === stateName &&
county.location.split(" ")[0] !== "Unassigned" &&
county.location.split(" ")[0] !== "Out"
) {
return (
<div className="card" key={index}>
<h3>{county.location.split(",")[0]}</h3>
<p>confirmed: {county.confirmed}</p>
<p>dead: {county.dead}</p>
</div>
);
} else {
return null;
}
})
)}
</div>

Conditional Rendering in ReactJs for one part in Html

I want to render some part of Html only if one of the variable is true. I have seen examples where I can return the whole element but I only want a if condition on one part of the html. I only want to show with 10 lines if one of the variables is true but html with 500 lines is common. Can I do that in return function?
const getCustomers= (props) => {
useEffect(() =>{ do something...});
return (
<>
if(test === true){
<div> 10 lines</div>
else
{
do not show this div
}
}
<div> 500 lines</div> // Common
</>
)
};
Conditional rendering is only supported using ternary operator and logical and operator:
{
something ? '10 lines' : '500 lines'
}
{
something && '10 lines' || '500 lines'
}
if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.
For further details, you may read this, and the docs
Try to avoid logic inside of your return statements.
You can assign your conditional output to a JSX value, and always render it.
const Customers = () => {
const optionalDiv = test === true && <div>10 lines</div>;
return (
<>
{optionalDiv}
<div>500 lines</div>
</>
);
};
you can use conditional (ternary) operator
return (
<>
{ test === true ? (<div> 10 lines</div>) : null }
<div> 500 lines</div>
</>
)
I think just doing it like this should do it -
return (
<>
{test? <div> 10 lines</div> : null}
<div> 500 lines which are common</div>
</>
);

Can i use multiple state value inside conditional rendering - ReactJs

I wonder how can use two state based booleans inside of the conditional rendering . For example i want to render a certain <div> element if one of the conditions are truthy and otherwise don't render it
Example :
{
this.state.visible && this.state.checked &&
<div>
...
</div>
}
In order to display my error message i use this example , but init i have the .length of the object so it is easy to use like :
{
this.state.ErrorMessage.length > 0 &&
<p>Error 404</p>
}
Can somebody give me heads up ? I am a little bit confused .
You can follow your way by parenthesis, to check both are true:
{
(this.state.visible && this.state.checked) && <div>...</div>
}
if you want one of is true:
{
(this.state.visible || this.state.checked) && <div>...</div>
}
Use it as a separate function which returns the components based on condition.
Example :
renderConditionalComponent() {
const { visible, checked } = this.state;
if (visible || checked) {
return <Component1 />;
}
// There could be other condition checks with different components.
// ...
return null;
}
render() {
// ...
return (
<div>
{this.renderConditionalComponent()}
{/* other components, etc */}
<OtherComponent />
</div>
);
}

React single line component

Hello I have a component which doesnt return anything. Im following a tutorial and the person is using newer syntax which confuses me a bit. The component looks like this:
const Alert = ({alerts}) => alerts !== null && alerts.length > 0 && alerts.map(alert => (<div key={alert.id} className={`alert-${alert.type}`}>{alert.msg}</div>));
I simply want to know how to write this without it being single line. So i can see what's going on. Much appreciated in advance. For as far as i am aware you always need to return something.
const Alert = ({ alerts }) => {
if (alerts !== null && alerts.length > 0) {
return alerts.map(alert => (
<div key={alert.id} className={`alert-${alert.type}`}>
{alert.msg}
</div>
));
}
return null
};
Things at play here are:
Arrow Functions
Array.Map
JSX
Template Literals
Basically its a component that takes in an alerts property (Array) as a prop (<Alert alerts={[...]} />). It checks whether the passed array is present and is not empty and then maps over it. For every item in the array, we are rendering a div containing the alert message.
Hope this helps!
Very roughly (i.e., untested):
const Alert = ({alerts}) => {
if ((alerts === null) || (alerts.length === 0)) {
return null
}
return alerts.map(alert => (
<div
key={alert.id}
className={`alert-${alert.type}`}
>
{alert.msg}
</div>
))
}
const Alert = ({alerts}) => {
if (!alerts || !alerts.length) return null
return (
<>
{alerts.map(alert => (
<div key={alert.id} className={`alert-${alert.type}`}>{alert.msg}</div>
)}
</>
)
}
I think what you are struggling with is generally the one-liner syntax, which doesn't need a return if there are no braces present.
What I mean is that this line
return alerts.map(alert => {
return (<div key={alert.id} className={`alert-${alert.type}`}>{alert.msg} </div>)
})
Would be the same as this line
return alerts.map(alert => (<div key={alert.id} className={`alert-${alert.type}`}>{alert.msg} </div>))

map function loop when rendering with ReactJS and concat JSX syntax

very simple question, when I loop through array when rendering react compnent with .map function, say:
render() {
let board = this.props.board;
return (
<div>
{
board.map((piece,index) => {
return (
<Piece data={piece}/>
);
})
}
</div>
);
}
I'm trying to add a break line every 5 pieces so (index % 5 == 0) add <br /> before the <Piece />
when I try to concatinate with + or to do something like this:
board.map((piece,index) => {
return (
(index % 5 == 0) ? <br /> : ''
<Piece data={piece}/>
);
})
I'm getting an output of matrix of [Object object]'s
Return an array of [ <br />, <Piece> ] if the condition holds and return just the Piece component otherwise. See the fiddle.
The relevant piece of code is this:
return <div>{items.map(function (i, index) {
if (index % 5 === 0) {
return [ <br key={index + "break"} />, <Item key={index} num={i} /> ];
}
return <Item key={index} num={i} />;
})}</div>;
Also, put key on the components you return from map or other ways that return array-like instances. This way, React doesn't need to take out all the generated components and replace them on each render, but can just find them under the key and update their attributes. Check out Reconciliation in React docs to learn more.

Categories