Hide View in #react-pdf/renderer - html

If I want to hide a text on the last page of the pdf we do this:
<Text
style={styles.paragraph}
render={({ pageNumber, totalPages }) =>
pageNumber === totalPages ? '' : 'Show this text'
}
/>
I am trying to hide a view on the last page, let's suppose this is the View I want to hide on the last page
<View
style={styles.paragraph}
render={({ pageNumber, totalPages }) =>
pageNumber === totalPages ? '' : 'Show this text'
}
/>
But it's not working. Any ideas?

How about this?
{ pageNumber !== totalPages ?(
<View
style={styles.paragraph}
render={({ pageNumber, totalPages }) =>{ Your content here}
}
/>
):null}

Related

How to display output in browser?

I retrieved my data from the database using the code below. It will return the number of "Active" and "Banned" account in console.log.
GetUserList = async user_type => {
this.setState({ loading: true });
const res = await userMgmt.getUserList(user_type);
console.log(res);
const activeAccount = res.data.data.filter(({ banned }) => !banned).length;
const bannedAccCount = res.data.data.filter(({ banned }) => banned).length;
console.log("Active : ", activeAccount);
console.log("Banned : ", bannedAccCount);
if (res.status === 200) {
if (this.mounted && res.data.status === "ok") {
this.setState({ loading: false, user_list: res.data.data });
}
} else {
if (this.mounted) {
this.setState({ loading: false });
}
ResponseError(res);
}
};
I want to display "activeAccount" and "bannedAccount" here but not sure how to.
const pageHeader = (
<PageHeader
style={{ backgroundColor: "#fff", marginTop: 4 }}
title="User Management - Admin"
<span>{`Banned User : `}</span>, //display banned here
<span>{`Active User : `}</span>, //display active here
/>
);
Insert both activeAccount and bannedAccCount into the state as follows.
const activeAccount = res.data.data.filter(({ banned }) => !banned).length;
const bannedAccCount = res.data.data.filter(({ banned }) => banned).length;
console.log("Active : ", activeAccount);
console.log("Banned : ", bannedAccCount);
if (res.status === 200) {
if (this.mounted && res.data.status === "ok") {
this.setState({
loading: false,
user_list: res.data.data,
activeAccount,
bannedAccCount,
});
}
}
Then show it inside the react component as follows.
const pageHeader = (
<PageHeader
style={{ backgroundColor: "#fff", marginTop: 4 }}
title="User Management - Admin"
<span>Banned User : {this.state.bannedAccCount}</span>, //display banned here
<span>Active User : {this.state.activeAccount}</span>, //display active here
/>
);

Objects are not valid as a React child (found: object with keys { my keys })

when I submit my form with the const onSubmit, I fetch data. If the submit form is ok, I want to extract the data I get from my api. So I use, setState reponse : my data, and then I want to pass this data (reponse) to the component SingleLayout.
But it doesn't work. I get this error : [Error: Objects are not valid as a React child (found: object with keys {ID, Post Title, post_date, Prix, Surface, Ville, Category, featured_image, mandats_signes, date_de_signature_du_compromis}). If you meant to render a collection of children, use an array instead.]
Here the code :
export default class QueryChild extends Component {
state = {
username: "",
password: "",
isLogged: null,
email: "",
reponse: '',
id: 4577
}
constructor(props) {
super(props);
this.render();
}
onSubmit = async() => {
const fetchValue = 'myAPI/suivi-dossier?' + 'username=' + this.state.username + '&password=' + this.state.password + '&id=' + this.state.id
try {
await fetch(fetchValue, {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.success === true) {
// I want to extract this :
this.setState({ reponse: responseJson.message })
this.setState({ isLogged: true })
} else {
this.setState({reponse : responseJson.message });
console.log(this.state.reponse)
}
// this.setState({
// data: responseJson
// })
})
.catch((error) => {
console.error(error);
});
} catch (err) {
console.log(err)
}
}
render() {
if(this.state.isLogged === true) {
// when user is Logged, I want to pass this.state.reponse to my component SingleLayout
// but I get the error : [Error: Objects are not valid as a React child
// (found: object with keys {ID, Post Title, post_date, Prix, Surface, Ville,
// Category, featured_image, mandats_signes, date_de_signature_du_compromis}). If you
// meant to render a collection of children, use an array instead.]
const SingleComponent = this.state.reponse.map(message => <SingleLayout key={message.ID} table={message}/> )
return (
<SafeAreaView>
{SingleComponent}
</SafeAreaView>
);
} else {
return (
<View style={styles.container}>
<ScrollView>
<ImageBackground source={image} resizeMode="cover" style={styles.image}>
<Spacer taille={70} />
<View style={styles.content}>
<Image
style={styles.imgLogo}
source={require('../../logo.png')}
/>
<Text style={styles.logo}>Pour des raisons de sécurité, veuillez entrer vos Identifiants</Text>
<View style={styles.inputContainer}>
<Text style={styles.textBasique}>{this.state.reponse}</Text>
<TextInput
placeholder='Identifiant ou adresse email'
style={styles.input}
value={this.state.username}
onChangeText={val => this.setState({ username: val})}
/>
<TextInput
placeholder='Mot de passe'
style={styles.input}
value={this.state.password}
secureTextEntry= {true}
onChangeText={val => this.setState({ password: val})}
/>
<Spacer taille={10} />
<Button title='Se Connecter' onPress={this.onSubmit}/>
<Spacer taille={10} />
</View>
</View>
<Spacer taille={200} />
</ImageBackground>
</ScrollView>
</View>
)
}
}
}
Thank you.
The response that comes from the server is an object. Since the "map" function only works with an array so, if you want to run this code you've to wrap "responseJson.message" into the array.
if(responseJson.success === true) {
this.setState({ reponse: [responseJson.message] })
this.setState({ isLogged: true })
}
Yes I get similar error after applying the solution because I found that the error comes from the setState reponse. So I added JSON.stringify and now the error is gone.
The code of Single Layout :
const SingleLayout = (props) => {
let id = props.id
let table = props.table
console.log(table)
const { colors } = useTheme();
return (
<View style={[styles.container, {backgroundColor: colors.background}]}>
<Text>Bravo</Text>
</View>
)
}
Now with the solution : const SingleComponent = Object.keys(this.state.reponse).map(key => )
it works but it send caracters one by one
SO I finally solved my problem :
the code i change :
QueryChild.tsx :
if(responseJson.success === true) {
//here :
this.setState({ reponse: JSON.stringify(responseJson.message) })
this.setState({ isLogged: true })
and I directly return SingleLayout like that :
return (
<SafeAreaView>
<SingleLayout table={this.state.reponse} />
</SafeAreaView>
Now I can access this.state.reponse into my SingleLayout :
const SingleLayout = (props) => {
let id = props.id
let table = props.table
const myObj = JSON.parse(table);
console.log(myObj[0].mandats_signes)
console.log(myObj[0].ID)
console.log(myObj[0].Category)
//etc...
const { colors } = useTheme();
return (
<View style={[styles.container, {backgroundColor: colors.background}]}>
<Text>Bravo</Text>
</View>
)
}
it's not a good practice to pass JSON and then parse.
I solved it and here is the link with the same solution that I presented to you:
https://codesandbox.io/s/peaceful-bouman-qyi5y?file=/src/App.js

how to add css for div in React?

how to add css in such a way whenever i click and select on div the border and background colors of the div should be changed same goes for all for the selected and should be back to previous if deselected.
This is a seemingly stupid question, but I'm not a pro when it comes to css. I have created a multiple div for multiple selection of div, but the css file that came with it has completely changed the look of it and it looks different to my other controls - Is there a simple way of inheriting the look of another control?
codesanbox
I tried this way
const data = [
{
key: 1,
value: "four"
},
{
key: 2,
value: "fours"
}
];
export default function App() {
const initialState = data.map((item) => {
return { ...item, selected: false };
});
const [work, setWork] = React.useState(initialState);
const [state, setState] = React.useState();
const [selected, setSelected] = React.useState("");
console.log("work");
console.log(work);
console.log("work");
console.log("state");
console.log(state);
console.log("state");
React.useEffect(() => {
setState(
work.filter((person) => person.selected).map((person) => person.value)
);
setSelected(
work.filter((person) => person.selected).map((person) => person.value)
);
}, [work]);
const handleSelect = (value) => {
console.log("value", value);
const nextState = work.map((item) => {
if (item.value === value) {
return {
...item,
selected: !item.selected
};
}
return item;
});
setWork(nextState);
};
return (
<div className="parent">
{work.map((da) => (
<div
className={`child ${selected === da.value ? "selected" : ""}`}
onClick={() => handleSelect(da.value)}
>
{da.value}
</div>
))}
</div>
);
}
I've done slight modifications in the code.
Following code would help you get the desired results.
const handleSelect = (key) => {
const updatedItems = [];
work.forEach((item) => {
updatedItems.push ({
...item,
selected: item.key === key
});
});
setWork(updatedItems);
};
return (
<div className="parent">
{work.map((da) => (
<div
className={`child ${da.selected ? "selected" : ""}`}
onClick={() => handleSelect(da.key)}
>
{da.value}
</div>
))}
</div>
);

Autocomplete text not coming on top while selecting the data

I'm new to react native I'm working on AutoCompleteTextView . I have one json file I need to display the country name in autocomplete view . I have display the country names of all countries. But while selecting the country it's not selecting. The json file which i'm displaying is.
My code for autocomplete is.
render() {
const { query } = this.state;
return (
<KeyboardAwareScrollView
innerRef={ref => this.scrollView = ref} //... Access the ref for any other functions here
contentContainerStyle={{flex: 1}}>
<View>
<View style={styles.autocompleteContainer}>
<Autocomplete
data={timezones}
defaultValue={query}
autoCapitalize="none"
autoCorrect={false}
onChangeText={text => this.setState({ query: text })}
placeholder="Enter Country"
renderItem={({ name, latlng }) => {
const prodNames = latlng.map(item => item.prodNames);
<TouchableOpacity onPress={() => this.setState({ query: text })}>
<Text>{name} {prodNames}</Text >
</TouchableOpacity>
}}
/>
</View>
<View>
<Text>Some content</Text>
</View>
Are you getting an error?
Try replacing this:
<TouchableOpacity onPress={() => this.setState({ query: text })}>
By this:
<TouchableOpacity onPress={() => this.setState({ query: name+''+prodNames })}>

FlatList Onpress show page with json data for each user

I have a endusers page where I fetch from an api and how the results in a flatlist as listitem.
I want to have one page for each user which shows their info but without creating userX.js for each user. So there should be only 1 page which is dynamically.
My Endusers.js View:
return (
<View style={styles.container}>
<View style={styles.headerContainer}>
<SearchBar
showLoading
placeholder={`Suchen: Name, Email oder Land...`}
lightTheme
round
onChangeText={text => this.searchFilterFunction(text)} />
</View>
<View style={styles.listContainer}>
<FlatList
style={styles.list}
data={this.state.data}
renderItem={({ item }) =>
<ListItem
titleStyle={styles.item}
subtitleStyle={styles.item}
title={`${item.strName} | ${item.strLand}`}
subtitle={`${item.strEmail}`}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.props.navigation.push('Userpage')}
/>}
keyExtractor={id => id}
/>
</View>
</View>
)
My Fetch method:
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: upper(responseJson.sort((a, b) => (a.strName - b.strName))),
loading: false,
error: responseJson.error
})
this.searchArray = responseJson;
})
.catch((error) => {
console.log(error)
})
My Constructor:
constructor() {
super()
this.state = {
loading: true,
data: [],
error: null
}
this.searchArray = [];
}
In Endusers.js View when I click on listitem the Userpage.js should show with the info of the clicked user.
How should I go on about this problem? What are the keywords I need to
google/research to find a solution? I'm not her to just copy paste so
please don't get this question wrong^^
You can send params when you push the navigation:
this.props.navigator.push({
component: MyScene,
title: 'Scene ' + nextIndex,
passProps: {index: nextIndex},
});
You can send as passProps your item which i guess contains the details regarding your User, like this:
passProps: {item: item}
Hope I helped, and more details on react-native documentation https://facebook.github.io/react-native/docs/navigation.