How to display button opposite of level in React? - reactjs

How to display button opposite of its status. Suppose its showing open then the button should appear Withdraw and if the status is appearing Withdraw button should appear Open in Reactjs.
I have a Json object which carries the necessary information.
Here is code is what I have had tried..
const initial = {
description: [
{
name: 'Alex',
level: 'open',
},
{
name: 'Sycus',
level: 'open',
},
{
name: 'Rasku',
level: 'Withdraw',
}
]
}
export default function App() {
const [state, setState] = React.useState(initial)
const [show , setshow] = React.useState(true)
const handleClick = () => {
return
}
const butFunction = () => {
return state.description.map(sub => {
const { level } = sub
return (
if(level === 'open'){
<button>Withdraw</button>
}
else{
<button>Open</buton>
}
)
})
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div>
<table>
<tbody>
{
state.description.map(desc => (
<tr>
<td>
{desc.name}
</td>
<td>
{desc.level}
</td>
<td>
{ show && butFunction()}
</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
);
}

Instead of rendering two different buttons for two conditions you can use ternary operator to conditionally change the text of single button like this:
return(
<button>{level===‘open’?’withdraw’:’open’}</button>
)

I don't think you need the map inside the butFunction. That would print 3 buttons for every entry. Instead, pass the function a parameter telling it which level it is.
Example below:
export default function App() {
const [state, setState] = React.useState(initial)
const [show , setshow] = React.useState(true)
// Use the level passed in
const butFunction = (level) => {
if(level === 'open'){
return <button>Withdraw</button>;
} else {
return <button>Open</button>;
}
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div>
<table>
<tbody>
{state.description.map(desc => (
<tr>
<td>
{desc.name}
</td>
<td>
{desc.level}
</td>
<td>
{show && butFunction(desc.level)} // <- Pass it here
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
Not it will only return one button per entry.

Related

Deleting necessary data (with checkbox) in React

Need to delete the data that is highlighted by the checkbox. When I click on the checkbox, in all checkboxes the done becomes: true, then false and i can't remove the highlights. When the remove function is worked, only the first element is deleted. How can write a remove function.
import React from "react";
import { useState } from "react";
const App = () => {
const [user, setUser] = useState([
{id:1, name:"Peter", surname:"Robinson"},
{id:2, name:"Ann", surname:"Walker"},
{id:3, name:"James", surname:"Allen"},
])
const [check, setCheck] = useState({done: false})
const remove = () => {
if (check.done) {
}
}
return <>
<table className="table table-bordered">
<thead>
<tr>
{Object.keys(user[0]).map((elm,i) => {
return <td key={i}>
{elm.charAt(0).toUpperCase() + elm.slice(1)}
</td>
})}
</tr>
</thead>
<tbody>
{
user.map((elem, ind) => {
return <tr key={ind}>
<td>{elem.id}</td>
<td>{elem.name}</td>
<td>{elem.surname}</td>
<td>
<input type="checkbox" name="" id="" onChange={() => setCheck({done: check.done ? false : true})}/>
</td>
</tr>
})
}
</tbody>
</table>
<button className="btn btn-primary ms-2" onClick={() => remove()}>Delete selected</button>
</>
}
export default App;
Thank you.
You should handle the checked state for each user independently, then delete the ones with the checked flag at true:
import React from 'react';
import { useState } from 'react';
const App = () => {
const [user, setUser] = useState([
{ id: 1, name: "Peter", surname: "Robinson", checked: false },
{ id: 2, name: "Ann", surname: "Walker", checked: false },
{ id: 3, name: "James", surname: "Allen", checked: false }
]);
const toggleCheck = (id) => {
const checkedIdx = user.findIndex((u) => u.id === id);
if (checkedIdx === -1) return;
const updatedUser = [...user];
updatedUser[checkedIdx].checked = !updatedUser[checkedIdx].checked;
setUser(updatedUser);
};
const remove = () => {
setUser([...user].filter((u) => !u.checked));
};
return (
<>
<table className="table table-bordered">
<thead>
<tr>
{Object.keys(user[0]).map((elm, i) => {
return (
<td key={i}>{elm.charAt(0).toUpperCase() + elm.slice(1)}</td>
);
})}
</tr>
</thead>
<tbody>
{user.map((elem, ind) => {
return (
<tr key={elem.id}>
<td>{elem.id}</td>
<td>{elem.name}</td>
<td>{elem.surname}</td>
<td>
<input
type="checkbox"
name=""
id=""
onChange={() => toggleCheck(elem.id)}
value={elem.checked}
/>
</td>
</tr>
);
})}
</tbody>
</table>
<button className="btn btn-primary ms-2" onClick={() => remove()}>
Delete selected
</button>
</>
);
};
export default App;
Here is the code to a working sandbox.

how to get output of table on page in reactjs

I create a table I get data from the database using the backend I just want to show the output of the table on the page the output will not be visible
This is the code of my table.js
//import Data from './TextForm';
function Table(props) {
console.log('type ', typeof (props.Data));
console.log('data ', props.Data)
return (
<table>
<thead>
<tr>
<th>Text No</th>
<th>TextArea</th>
</tr>
</thead>
<tbody>
{props.Data ?
Object.entries(props.Data).map((key,value)=> {
console.log('Key',key);
{
<tr key={value}>
<td>{key.textId}</td>
<td>{key.textArea}</td>
</tr>
}
})
: null
}
</tbody>
</table>
)
}
export default Table;
this is props. data where I get the data and define prop. data I get data from the backend I connected the frontend for getting and storing data
Edit
function TextForm(props) {
const [text, setText] = useState('');
const [submittext,setsubmittext]=useState(null);
const [Data,setData]=useState([]);
const handleOnClickUpperCase = () => {
var newText = text.toUpperCase();
setText(newText);
}
const handleOnClickLowerCase = () => {
var newText = text.toLowerCase();
setText(newText);
}
const handleOnChange = (e) => {
setText(e.target.value);
}
const handleOnPreview = (e) => {
e.preventDefault();
setsubmittext(text);
// console.log(text);
const ROOT_URL='https://localhost:7113/';
var formData={
Textarea:text
}
axios.post(`${ROOT_URL}api/demo-text`, formData, {
headers: {"Access-Control-Allow-Origin": "*", 'Content-Type': 'application/json'}
})
.then(function (response) {
console.log('successs')
//handle success
setData(response);
console.log('response ',Data);
})
.catch(function (response) {
console.log('error')
//handle error
console.log(response);
})
}
return (
<>
<div className="container">
<h1>{props.title}</h1>
<p>Enter Text Here:</p>
<div className="mb-3">
<textarea className="form-control" value={text} onChange={handleOnChange} id="mybox" rows="8"></textarea>
</div>
<Table Data={Data} />
{text === text.toLowerCase() ? <button className="btn btn-primary" onClick={handleOnClickUpperCase}>Convert to Upper Case</button> : <button className="btn btn-primary" onClick={handleOnClickLowerCase}>Convert to Lower Case</button>}
<button className="btn btn-primary mx-3" onClick={handleOnPreview}>submit</button>
</div>
<hr></hr>
<div className="container my-4" >
<h1>{props.sum}</h1>
<p>Text Word {text.split(" ").length} and Character is {text.length}</p>
<p>{0.008 * text.split(" ").length} Minutes to Read</p>
</div>
<hr></hr>
<div className="container my-4">
<h2>Preview Your Text</h2>
<p>{submittext}</p>
</div>
</>
)
}
the output of prop.data
here have iterator objects array so pls try the following the code see I created an example as your same array object as you shared img pls find an example here link.
import React from "react";
import ReactDOM from "react-dom";
const Data = {
data: {
result: [
{ textId: 1, textarea: "test" },
{ textId: 2, textarea: "1234" },
{ textId: 3, textarea: null },
{ textId: 4, textarea: null },
]
}
};
function Table(props) {
console.log("type ", typeof props.Data);
console.log("data ", props.Data);
return (
<table>
<thead>
<tr>
<th>Text No</th>
<th>TextArea</th>
</tr>
</thead>
<tbody>
{props?.Data?.data?.result?.map((item) => (
<>
<tr key={item.textId}>
<td>{item.textId}</td>
<td>{item.textarea}</td>
</tr>
</>
))}
</tbody>
</table>
);
}
function App() {
return (
<>
<Table Data={Data} />
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
So you have to iterate over props.Data.data.result instead of props.Data, You don't need the Object.entries(),
and make the initial value of the Data = {} instead of [].
const [Data, setData] = useState({});
In the conditional JSX code, you need to check if the object has keys or not, and you don't need Object.entries method, just go with props.Data.data.result.map(), Also you have to return tr from the map method as #Usama mentioned.
{Object.keys(props.Data).length ?
props.Data.data.result.map((key,value)=> {
return (<tr key={value}>
<td>{key.textId}</td>
<td>{key.textArea}</td>
</tr>)
})
: null
}

display icon based on file type

I want to display icons based on the file type. From the object that I am fetching from strapi I can get the file extension. But I want to render it dynamically on the table.
const TableData = () => {
const [data, setData] = useState([]);
const getData = () => {
axios.get("http://localhost:1337/document-uploads").then((response) => {
console.log(response);
const myData = response.data;
setData(myData);
});
};
useEffect(() => getData(), []);
return (
<div className="my-5">
<Table striped bordered hover>
<thead>
<tr>
<th>Icon</th>
<th>File Name</th>
<th>Description</th>
<th>Author</th>
<th>Date created</th>
</tr>
</thead>
<tbody>
{data &&
data.map((file: File) => (
<tr key={file.id}>
<td>
{() => {
if (file.document.ext == ".pdf") {
return <img src={PDF} />;
} else if (file.document.ext == ".xml") {
return <XML />;
} else {
return <JPEG />;
}
}}
</td>
<td>{file.document.name}</td>
<td>{file.description}</td>
<td>{file.author}</td>
<td>{file.created_at}</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
export default TableData;
I am getting the error: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it."
You can try the code without the anonymous function inside, just start from the if statement without everything wrapped inside a function.
{
if (file.document.ext == ".pdf") {
return <img src={PDF} />;
} else if (file.document.ext == ".xml") {
return <XML />;
} else {
return <JPEG />;
}
}
You can as well try different approaches with more modern javascript and ternary operators:
{
file.document.ext == ".pdf" ? <img src={PDF} /> :
file.document.ext == ".xml" ? <XML /> : <JPEG />
}
Which is the same as the first code block.

Conditional statement within react render meth

I am new to react and I am trying to add a condition within the render method so that if the value framework1 is empty I need not add a text within the HTML.
Below is my code.
buildResults = () => {
const {
results
} = this.state;
return {
<div className={`${block}__results`}>
<table>
<thead></thead>
<tbody>
{ results.map(item => this.buildResult(item)) }
</tbody>
</table>
</div>
}
buildResult = (data) => {
const {
framework1,
framework2
} = data;
return (
<tr className={`${block}__row`}>
<td className={`${block}__cell ${block}__cell--ticker`}>
/* I need to display the text "view" only if framework1 is not empty */
View
</td>
</tr>
)
}
Use an if statement to check whether the there is data, in this case, I am checking whether the data in framework1 is a string.
buildResults = () => {
const {
results
} = this.state;
return {
<div className={`${block}__results`}>
<table>
<thead></thead>
<tbody>
{ results.map(item => this.buildResult(item)) }
</tbody>
</table>
</div>
}
buildResult = (data) => {
const {
framework1,
framework2
} = data;
return (
<tr className={`${block}__row`}>
<td className={`${block}__cell ${block}__cell--ticker`}>
if (framework1.indexOf("ST1") ){
// display something else
}
else {
View
}
</td>
</tr>
)
}

React 'this' Context within Method

I am trying to call a Method on a Button click like this (the button is returned within a method itself):
<button onClick={removeClick}>Remove</button>
this is the method i am trying to call
removeClick = event => {
console.log('clicked');
};
im always getting errors like '_this2 is undefined'
i have already tried binding the method in the constructor.
an arrow function within the onClick didn't work as well
removeClick = event => {
console.log('clicked');
};
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp - 273.15);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key={lon + lat}>
<td>
<GoogleMap lon={lon} lat={lat} />
<span className="city-name">{name}</span>
</td>
<td>
<WeatherChart data={temps} color="red" unit="°C" />
</td>
<td>
<WeatherChart data={pressures} color="orange" unit="hPA" />
</td>
<td>
<WeatherChart data={humidities} color="blue" unit="%" />
</td>
<td>
<button onClick={this.removeClick}>Remove</button>
</td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (°C) </th>
<th>Pressure (hPA)</th>
<th>Humidity (%)</th>
<th />
</tr>
</thead>
<tbody>{this.props.weather.map(this.renderWeather)}</tbody>
</table>
);
}
}
const mapStateToProps = ({ weather }) => ({
weather
});
const mapDispatchToProps = {
removeCity
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(WeatherList);
this is how the my component looks like
I hope anyone can help me
try
renderWeather = cityData => {
...
}
and because you are using your clickhandler for a set of data you may want to pass some kind of identifier to it
removeClick = id => event => {
console.log(`Removing data for ${id}`)
}
and call it by
<button onClick={() => {this.removeClick(id)}}>Remove</button>
Try to pass this as a second param to map
<tbody>{this.props.weather.map(this.renderWeather, this)}</tbody>
class Item extends React.Component {
removeClick = event => {
console.log('clicked');
}
renderWeather(cityData) {
return <button onClick={this.removeClick}>Remove</button>
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (°C) </th>
<th>Pressure (hPA)</th>
<th>Humidity (%)</th>
<th />
</tr>
</thead>
<tbody>{this.props.weather.map(this.renderWeather, this)}</tbody>
</table>
)
}
}
const weather = [
{
city: {name: '123'}
}
];
ReactDOM.render(
<Item weather={weather} />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>

Resources