React function not returning <div> element - reactjs

In the following code:
class App extends React.Component {
state = { val: '' };
handleChange = (e) => {
this.setState({ val: e.target.value });
}
OddEven(num) {
const number = parseInt(num);
let description;
if (Number.isInteger(number)) {
if (number % 2 == 0) {
description = <strong>even</strong>;
} else {
description = <i>odd</i>;
}
alert(number);
return (
<h1>
Test
</h1>
);
} else {
return null;
}
}
render() {
return (
<div>
<input type='text' onChange={this.handleChange} />
<button onClick={() =>this.OddEven(this.state.val) }>
Odd Even
</button>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
the OddEven() is not returning the div. Can't figure out why for the last 2 hours. I'm in the learning phase. So don't get offended if it's something silly.

if you want to return your description here is how to do it:
class App extends React.Component {
state = {
val: '',
description: null,
};
handleChange = (e) => {
this.setState({ val: e.target.value });
}
OddEven(num) {
const number = parseInt(num);
let {description} = this.state;
if (Number.isInteger(number)) {
if (number % 2 == 0) {
description = <strong>even</strong>;
} else {
description = <i>odd</i>;
}
this.setState({description: description});
} else {
this.setState({description: null});
}
}
render() {
return (
<div>
<input type='text' onChange={this.handleChange} />
<button onClick={() =>this.OddEven(this.state.val) }>
Odd Even Check?
</button>
{this.state.description}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);

That is because you are not rendering what your function returns anywhere, what you would rather want to do is this:
class App extends React.Component {
state = { val: "", oddeven: "" }
handleChange = e => {
this.setState({ val: e.target.value })
}
OddEven = () => {
const number = parseInt(this.state.val) //Use the state directly
let description
if (Number.isInteger(number)) {
if (number % 2 == 0) {
description = <strong>even</strong>
} else {
description = <i>odd</i>
}
alert(number)
this.setState({ oddEven: "Hello" })
} else {
return null
}
}
render() {
return (
<div>
<input type="text" onChange={this.handleChange} />
<button onClick={this.OddEven}>Odd Even</button> {/* you do not need to passs the state here, you can directly access it in your function */}
{this.state.oddEven && <h1>{this.state.oddEven}</h1>} {/* Here we check if oddEven exists and then we display whatever we set in the OddEven function}
</div>
)
}
}
Here we set the state to what you want to render and then use that inside our render function.

Try This :
class App extends React.Component {
state = { val: '' };
handleChange = (e) => {
this.setState({ val: e.target.value });
}
OddEven(num) {
const number = parseInt(num);
if (Number.isInteger(number)) {
if (number % 2 == 0) {
return <strong>even</strong>;
} else {
return <i>odd</i>;
}
} else {
return <a>Please Enter A Number</a>;
}
}
render() {
return (
<div>
<input type='text' onChange={this.handleChange} />
{OddEven(this.state.val)}
</div>
);
}

Related

function component vs function - the sense of using function components

My problem is I do not really understand if using function components instead function is good idea in below example:
first program without function components
class App extends React.Component {
state = {
check: false,
isFormSubmitted: false
}
handleChangeChecked = () => {
this.setState({
check: !this.state.check,
isFormSubmitted: false
})
return (true)
}
displayMsg = () => {
if (this.state.isFormSubmitted == true) {
if (this.state.check == true)
return (<p>You are allowed to watch this film!</p>)
else return (<p>You are not allowed to watch this film.</p>)
} else return (null)
}
handleFormSubmit = (e) => {
e.preventDefault()
this.setState({
isFormSubmitted: true
})
}
render() {
return (
<React.Fragment>
<h1>Film</h1>
<form onSubmit={this.handleFormSubmit}>
<input type="checkbox" onChange={this.handleChangeChecked} checked={this.state.check} />
<label>I have got 16 years old</label>
<button>Buy ticket</button>
</form>
{this.displayMsg()}
</React.Fragment>
)
}
}
ReactDOM.render(< App />, document.getElementById('root'));
second program with function components:
const PositiveMessage = () => <p>Mozesz obejrzeć film, zapraszam</p>;
const NegativeMessage = () => <p>Nie możesz obejrzeć tego filmu !</p>;
class TicketShop extends React.Component {
state = {
isConfirmed: false,
isFormSubmitted: false
}
handleCheckboxChange = () => {
this.setState({
isConfirmed: !this.state.isConfirmed,
isFormSubmitted: false
})
}
displayMessage = () => {
if (this.state.isFormSubmitted) {
if (this.state.isConfirmed) { return <PositiveMessage /> }
else { return <NegativeMessage /> }
} else { return null }
}
handleFormSubmit = (e) => {
e.preventDefault()
if (!this.state.isFormSubmitted) {
this.setState({
isFormSubmitted: !this.state.isFormSubmitted
})
}
}
render() {
return (
<>
<h1>Kup bilet na horror roku !</h1>
<form onSubmit={this.handleFormSubmit}>
<input type="checkbox" id="age" onChange={this.handleCheckboxChange} checked={this.state.isConfirmed} />
<label htmlFor="age">Mam conajmniej 16 lat</label>
<br />
<button type="submit">Kup bilet</button>
</form>
{this.displayMessage()}
</>
)
}
}
ReactDOM.render(<TicketShop />, document.getElementById('root'))
i made two programs with and without function components and i dont see the difference of working.
In user point of view both programs works without any difference.

TestDont - Change Username - REACT

Looking for thinking tips towards refactoring the App function. The component must remain unchanged. This example is clunky and a mashup of several different online contributions to the use of ref.
I started here: https://reactjs.org/docs/refs-and-the-dom.html
Thanks in advance.
class Username extends React.Component {
state = { value: "" };
changeValue(value) {
this.setState({ value });
}
render() {
const { value } = this.state;
return <h1>{value}</h1>;
}
}
function App() {
this.username = React.useRef();
this.component = React.useRef()
clickHandler = e => {
//console.log(this.component.current.changeValue())
this.component.current.changeValue(this.username.current.value)
}
return (
<div>
<button onClick={clickHandler}>Change Username</button>
<input type="text" ref={this.username}/>
<Username ref={this.component}/>
</div>
);
}
document.body.innerHTML = "<div id='root'></div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
document.querySelector("input").value = "John Doe";
document.querySelector("button").click();
setTimeout(() => console.log(document.getElementById("root").innerHTML));
Try this code.
function Username({ value }) {
return (
<h1>{value}</h1>
);
}
class App extends React.Component {
state = {
usernameDynamic: '',
usernameStatic: '',
}
onChangeUserName = () => {
this.setState({ usernameStatic: usernameDynamic });
}
onChangeUserNameDynamic = (e) => {
this.setState({ usernameDynamic: e.target.value });
}
render() {
return (
<div>
<button onClick={this.onChangeUserNameStatic}>Change Username</button>
<input type="text" value={this.state.usernameDynamic} onChange={this.onChangeUserNameDynamic} />
<Username value={this.state.usernameStatic} />
</div>
);
}
}

How can I update a paragraph tag in REACT when an input field is changed?

I would like the paragraph tag to update the number of characters being typed into the input. My handler prints the correct length into the console so that part works. Here is what I have so far:
class App extends Component {
textLengthHandler = (event) => {
let length = 0;
if (event) {
length = event.target.value.length
};
console.log("length is " + length);
return length;
}
render() {
return (
<div className="App">
<input type='text' onChange={this.textLengthHandler} value={this.text}/>
<p>length is {this.textLengthHandler()}</p>
</div>
);
}
}
export default App;
You need to setState. Don't return the length.
class App extends Component {
constructor() {
this.state = {
textLength: 0,
text: '',
}
}
textLengthHandler = (event) => {
let length = 0;
const text = event.target.value;
if (event) {
length = text.length
};
console.log("length is " + length);
this.setState({
textLength: length,
text: text,
});
}
render() {
return (
<div className="App">
<input type='text' onChange={this.textLengthHandler} value={this.state.text}/>
<p>length is {this.state.textLength}</p>
</div>
);
}
}
export default App;
Let me know if you have any questions.

Showing two different components based on return value in react js

I have search function where on entering text it returns the object from an array(json data) and based on the condition (whether it as an object or not) I need to show two different components ie. the list with matched fields and "No matched results found" component.
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
searchTextData: '',
isSearchText: false,
isSearchOpen: false,
placeholderText:'Search Content',
filteredMockData: [],
dataArray: []
};
}
handleSearchChange = (event, newVal) => {
this.setState({ searchTextData: newVal })
if (newVal == '') {
this.setState({ clearsearch: true });
this.setState({
filteredMockData: []
});
this.props.onDisplayCloseIcon(true);
} else {
this.props.onDisplayCloseIcon(false);
searchData.searchResults.forEach((item, index, array) => {
this.state.dataArray.push(item);
});
this.setState({ filteredMockData: this.state.dataArray });
}
}
clearInput = () => {
this.setState({ searchTextData: '' })
}
isSearchText = () => {
this.setState({ isSearchText: !this.state.isSearchText });
}
onSearchClick = () => {
this.setState({ isSearchOpen: !this.state.isSearchOpen });
this.setState({ searchTextData: '' });
this.props.onDisplayCloseIcon(true);
}
renderSearchData = () => {
const SearchDatasRender = this.state.dataArray.map((key) => {
const SearchDataRender = key.matchedFields.pagetitle;
return (<ResultComponent results={ SearchDataRender } /> );
})
return SearchDatasRender;
}
renderUndefined = () => {
return ( <div className = "search_no_results" >
<p> No Recent Searches found. </p>
<p> You can search by word or phrase, glossary term, chapter or section.</p>
</div>
);
}
render() {
return ( <span>
<SearchIcon searchClick = { this.onSearchClick } />
{this.state.isSearchOpen &&
<div className = 'SearchinputBar' >
<input
placeholder={this.state.placeholderText}
className= 'SearchInputContent'
value = { this.state.searchTextData}
onChange = { this.handleSearchChange }
/>
</div>
}
{this.state.searchTextData !== '' && this.state.isSearchOpen &&
<span className='clearText'>
<ClearIcon className='clearIcon' clearClick = { this.clearInput }/>
</span>
}
{this.state.searchTextData !== '' && this.state.isSearchOpen &&
<div className="SearchContainerWrapper">
<div className = "arrow-up"> </div>
<div className = 'search_result_Container' >
<div className = "search_results_title" > <span> Chapters </span><hr></hr> </div>
<div className="search_show_text" >
<ul className ="SearchScrollbar">
{this.state.filteredMockData.length ? this.renderSearchData() : this.renderUndefined() }
</ul>
</div>
</div>
</div>}
</span>
);
}
}
Search.propTypes = {
intl: intlShape.isRequired,
onSearchClick: PropTypes.func,
isSearchBarOpen: PropTypes.func,
clearInput: PropTypes.func,
isSearchText: PropTypes.func
};
export default injectIntl(Search);
Search is my parent component and based on the matched values I need to show a resultComponent like
class ResultComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render(){
console.log(this.props.renderSearchData(),'Helloooo')
return(<p>{this.props.renderSearchData()}</p>)
}
}
ResultComponent.propTypes = {
results: PropTypes.string.isRequired
};
I'm getting an error "renderSearchData is not an function".I'm new to react and Hope someone can help.
The only prop passed to ResultComponent component is results
So in ResultComponent Component Replace
this.props.renderSearchData()
With
this.props.results

redux-form always returns same values for Multiselect react-widget

I am trying to use redux-form with react-widget Multiselect this example:
var Multiselect = ReactWidgets.Multiselect
, people = listOfPeople();
var Example = React.createClass({
getInitialState() {
return { value: people.slice(0,2) };
},
_create(name){
var tag = { name, id: people.length + 1 }
var value = this.state.value.concat(tag)
// add new tag to the data list
people.push(tag)
//add new tag to the list of values
this.setState({ value })
},
render(){
// create a tag object
return (
<Multiselect data={people}
value={this.state.value}
textField="name"
onCreate={this._create}
onChange={value => this.setState({ value })}/>
)
}
});
ReactDOM.render(<Example/>, mountNode);
Below is a code snippet for a parent component which makes usage of redux-form (EditVideo component) component (please look at the comments in onSubmit method):
class VideoEdit extends React.Component {
constructor(props) {
super(props);
}
onSubmit = (values) => {
console.log(values.categories) // always returns initialValues for categories, new values not adding
}
render() {
const { loading, videoEdit, categories } = this.props;
if (loading) {
return (
<div>{ /* loading... */}</div>
);
} else {
return (
<div>
<h2>Edit: {videoEdit.title}</h2>
<EditVideo
onSubmit={this.onSubmit}
initialValues={videoEdit}
categories={categories}
/>
</div>
);
}
}
}
And here is a code snippet of redux-form component with react-widget Multiselect component:
class CategoryWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.defValue,
extData: this.props.data
}
this._create = this._create.bind(this);
}
_create(name) {
var tag = { name, id: this.state.extData.length + 100 + 1 }
var value = this.state.value.concat(tag)
var extData = this.state.extData.concat(tag)
this.setState({
extData,
value
})
}
render() {
return (
<Multiselect
{...this.props.input}
data={this.state.extData}
onBlur={() => this.props.input.onBlur()}
value={this.state.value || []}
valueField="id"
textField="name"
onCreate={this._create}
onChange={value => this.setState({ value })}
/>
)
}
}
const EditVideoForm = (props) => {
const { handleSubmit, submitting, onSubmit, categories, initialValues, defBook } = props;
return (
<Form name="ytvideo" onSubmit={handleSubmit(onSubmit)}>
<div>
<Field
name="categories"
component={CategoryWidget}
data={categories}
defValue={initialValues.categories}
/>
</div>
<br />
<Button color="primary" type="submit" disabled={submitting}>
Submit
</Button>
</Form>
);
};
export default reduxForm({
form: 'videoEdit',
enableReinitialize: true
})(EditVideoForm);
The Multiselect widget works as expected, yet the form on submit always returns the same initial values for categories.
I believe the problem lays in the fact that CategoryWidget is a class base component? If so, what is a way to make it work?
Here is what I have done for my Multiselect at the end:
class CategoryWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.defValue,
extData: this.props.data
}
this._create = this._create.bind(this);
}
_create(name) {
var tag = { name, id: this.state.extData.length + 100 + 1 }
var value = this.state.value.concat(tag)
var extData = this.state.extData.concat(tag)
this.setState({
extData,
value
})
}
componentDidUpdate() {
let { onChange } = this.props.input
onChange(this.state.value)
}
handleOnChange(value) {
this.setState({ value })
}
render() {
const input = this.props.input
return (
<Multiselect
{...input}
data={this.state.extData}
onBlur={() => input.onBlur()}
value={this.state.value || []}
valueField="id"
textField="name"
onCreate={this._create}
onChange={value => this.handleOnChange(value)}
/>
)
}
}

Resources