Reactjsx set style depending on JSON-Value - json

Good afternoon, I am trying to write a SPA with React.
I get a JSON-Object from a webservice wich validates the Inputfields.
Now i want so set the Style of the Inputfield depending on the answer of the Webservice.
At example the Style shoud be:
style={{borderColor: 'green', boxShadow: '0 0 5px green',}}
when the JSONValue is 0
<Input
style = ???
...
/>
My JSON looks like this:
{
"validate": {
"isValidTest": 0
...
}
}
edit: the JSON can have three diffrent Values witch three different Styles.

This is an example of what you could do
Example 1
<Input
style =
{{borderColor: obj.validate.isValidTest === 0 ? 'red':'green'
boxShadow: `0 0 5px ${obj.validate.isValidTest === 0 ? 'red' : 'green'}`}}
...
/>
What's happening here
By utilizing the shorthand conditionals we can apply a borderColor & boxShadow to the style depending on the value of isValidTest within obj (which will be replaced by the name of your object)(!!)
Have a look at this example to see what is happening here
NOTE
Ofcourse, this could be separated from the inline style attribute by setting a className depending on the outcome of isValidTest or by applying a different style constant to it depending on the same conditional
Example 2
const errorStyles = {
borderColor: 'red',
boxShadow: '0 0 5px red'
}
const validStyles = {
borderColor: 'green',
boxShadow: '0 0 5px green'
}
<Input
style={ obj.validate.isValidTest === 0 ? errorStyles : validStyles }
/>
Again, in this sandbox both examples are shown in the same file, on the same page.
You could also have a look at this question & answer for more examples and information
EDIT
To account for more than two values in isValidTest you could go at it like so:
const errorStyles = {
borderColor: 'red',
boxShadow: '0 0 5px red'
}
const validStyles = {
borderColor: 'green',
boxShadow: '0 0 5px green'
}
const error2Styles = {
borderColor: 'magenta',
boxShadow: '0 0 5px magenta'
}
const valid2Styles = {
borderColor: 'yellow',
boxShadow: '0 0 5px yellow'
}
isValid = (valid) => {
switch(valid) {
case -1:
return errorStyles
break;
case 0:
return error2Styles
break;
case 1:
return validStyles
break;
case 2:
return valid2Styles
break;
}
}
<Input
style={this.isValid(obj.validate.isValidTest)}
/>
What happens in the above example
As seen above the style attribute refers to this.isValid which in turn return a const containing the styles, supplied to this function is the isValidTest property from your obj.validate.
I have updated the sandbox to include the above example
Hope this helps!

Related

I want to change the background for striped in react-data-table-component?

here the changes herder row BG color work for me but how we can change the BG color of the striped row.
import React from 'react';
import DataTable from 'react-data-table-component';
const tableCustomStyles = {
headRow: {
style: {
color:'#223336',
backgroundColor: '#e7eef0'
},
},
striped: {
default: 'red'
},
}
function App() {
return (
<div className="App">
<h3>DataTable in React - Clue Mediator</h3>
<DataTable
title="Employees"
columns={columns}
data={data}
pagination
highlightOnHover
striped
customStyles={tableCustomStyles}
/>
</div>
);
}
export default App;
here I used the react-data-table-component and want to change the customized BG color of the striped row.
how can we do that?
After looking through the documentation for using custom styles found here and the available fields here, it appears you need to nest the striped styles inside of a row object in the style config.
Edit for comment:
To change the order of striped and non-striped rows, you could just swap the colors of the regular rows and striped rows (i.e. set the regular row to have the striped attributes and vise-versa).
Your tableCustomStyles should look like this (for even row stripes):
const tableCustomStyles = {
headRow: {
style: {
color:'#223336',
backgroundColor: '#e7eef0'
},
},
rows: {
style: {
color: "STRIPEDCOLOR",
backgroundColor: "STRIPEDCOLOR"
},
stripedStyle: {
color: "NORMALCOLOR",
backgroundColor: "NORMALCOLOR"
}
}
}

font size and width control of datepickerrange

how to make start date and end date appear at one line for datepickerrange component.
for example, mine is the first figure, but i want it look like 2nd figure.
here is my code:
html.H4('Select a start and end date:'),
dcc.DatePickerRange(id='date-range',
min_date_allowed=datetime(2020,1,1),
max_date_allowed=datetime.today(),
start_date=start_date,
end_date=end_date,
style = {
'font-size': '6px','display': 'inline-block', 'border-radius' : '2px',
'border' : '1px solid #ccc', 'color': '#333',
'border-spacing' : '0', 'border-collapse' :'separate'
}
)
in CSS file, i also added this and it doesn't work, Thanks for help, please
.DateInput, .DateInput_1 {
width: 100%;
}
I added your code to a html.Div
import dash
from dash import dcc, html
from datetime import date, timedelta, datetime
app = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}])
app.layout = html.Div([html.H4('Select a start and end date:'),
dcc.DatePickerRange(id='date-range',
min_date_allowed=datetime(2020,1,1),
max_date_allowed=datetime.today(),
start_date=datetime(2020,1,1),
end_date=datetime(2020,1,1),
style = {
'font-size': '6px','display': 'inline-block', 'border-radius' : '2px',
'border' : '1px solid #ccc', 'color': '#333',
'border-spacing' : '0', 'border-collapse' :'separate'
} )
])
if __name__ == '__main__':
app.run_server(debug=False)
And I got it

How can you have an IF THEN ELSE in Angular with ngStyle?

I am trying to have rows in a table highlight based on a STATUS value. I can get it working with either yellow or no color by doing:
[ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : ''}"
How can I add another option where if STATUS === 2 it goes to red?
You can create a map object in the ts file
colorMap = {
'1': 'yellow',
'2': 'red',
}
<div [ngStyle]="{'background-color': colorMap[cnresult.STATUS] || ''}"></div>
By this you can add multiple conditions
You can do something like this as well,
[ngStyle] = "{'background-color': getBackground(cnresult.STATUS)}"
Then in your component.ts file,
getBackground(status) { (2)
switch (status) {
case 1:
return 'yellow';
case 2:
return 'green';
case 3:
return 'red';
}
}
You can chain multiple ternary operations
[ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : cnresult.STATUS === 2 ? 'red' : ''}"
Another, possibly more maintainable option would be to conditionally apply class(es) like so:
<div [class.yellow]="cnresult.STATUS === 1"
[class.red]="cnresult.STATUS === 2"
></div>
// This belongs in your .css file
.yellow {
background-color: yellow;
}
.red {
background-color: red;
}

How to delete this div in React

When the button is clicked I want an area to write an e-mail. And when the delete icon is clicked, this area is deleted. How can i do
addListItem = () => {
var number=0;
var list = [...this.state.list];
number++;
var ele=
<div id={number}>
<span>{number}
<TextField id="standard-basic" style={{width:"60%"}}></TextField>
</span>
<IconButton>
<Delete></Delete>
</IconButton>
</div>
list.push(ele)
this.setState({list})
}
<Button onClick={this.addListItem} style={{ float : "left" ,marginTop:10,backgroundColor: "#657c9e", borderRadius: 4, boxShadow: "#727272", width: 159, height: 46 , color: Color.AIRPLATFORM.WHITE , fontSize: 15 , fontWeight: 500,marginLeft:0}} variant="contained">ADD</Button><br></br><br></br><br></br>
<div id="list" style={{backgroundColor:"#ffffff",borderRadius:16,padding:10,minHeight:140,width:406,borderRadius:8,marginTop:10,boxShadow: "0px 1px 3px 0px rgba(0, 0, 0, 0.2), 0px 2px 1px -1px rgba(0, 0, 0, 0.12), 0 1px 0 rgba(0, 0, 0, 0.14)"}}>
{this.state.list}
</div>
Here is my code
You can do conditional rendering. So, what conditional rendering is, you render the JSX element based on a condition.
Conditional rendering
{condition ? <p>True</p> : <p>False</p>}
This one will render True paragraph if condition is ture, and False paragraph if condition is false
{condition && <p>True</p>}
This one will render True only if condition is True, and render nothing otherwise
In your case
In your case, first you need a state variable to store the render choice
const [renderDelete, setRenderDelete] = useState(true)
Then, on click you set renderDelete to false:
<button onClick={() => setRenderDelete(false)> Render Delete </button>
Lastly, you conditional render based on the renderDelete variable:
Instead of <Delete /> you render:
{renderDelete && <Delete />}
You can do the same logic to toggle between rendering Edit field or Delete field:
{renderDelete ? <Delete /> : <Edit />}

Can you create a checkbox without using a input type=checkbox html element?

I noticed this website has a list of checkboxes, but when I look at the HTML I just see div's with CSS classes on them.
How do you create checkboxes and check them off just by using CSS?
What is the benefit of doing it via CSS?
You certainly can. The advantage is that it gives you way more flexibility. For example, here's a basic React component that uses divs for the checkbox:
https://jsbin.com/xarewiweza/1/edit?html,js,output
const styles = {
outer: {
borderRadius: 5,
border: '2px solid gray',
width: 30,
height: 30,
cursor: 'pointer',
},
inner: checked => ({
borderRadius: '50%',
height: 28,
width: 28,
backgroundColor: checked ? 'red' : 'transparent',
margin: 1,
transition: 'background-color 0.2s ease',
})
}
class Checkbox extends React.Component {
constructor(props) {
super(props)
this.state = {
checked: false,
}
}
render() {
console.log(this.state)
return (
<div
onClick={() => this.setState({ checked: !this.state.checked, })}
style={styles.outer}>
<div style={styles.inner(this.state.checked)} />
</div>
)
}
}
ReactDOM.render(<Checkbox />, document.body)
If you wanted animated checkmarks, or other cool stuff, you'd have to go custom.
The disadvantage is that you don't get some of the default HTML functionality, though I'm not sure if there is anything useful with the checkbox specifically. For example, with the default select on iOS, it automatically uses the carousel selecter, which is a handy feature.