Testing a component with no logic - reactjs

Should you test components that have no logic? My component only renders jsx and some other components from a file above. Here's the example :
import React from 'react';
import SubscriptionForm from './SubscriptionForm';
import './style.scss';
import { FiPhone, FiMail } from 'react-icons/fi';
import { FaFacebook, FaTwitterSquare, FaLinkedin } from 'react-icons/fa';
export default function Footer() {
return (
<div className="footer-container">
<div className="footer-container__contact">
<h2>Contact us</h2>
<p>
<FiMail /> test#test.com
</p>
<p>
<FiPhone /> +31 6 - 1222 - 123
</p>
</div>
<div className="footer-container__subscription-form">
<h2>Subscribe and never miss a release</h2>
<SubscriptionForm />
</div>
<div className="footer-container__social">
<h2>Follow us</h2>
<div className="footer-container__social-icons">
<FaFacebook className="footer-container__social-icon" />
<FaTwitterSquare className="footer-container__social-icon" />
<FaLinkedin className="footer-container__social-icon" />
</div>
</div>
</div>
);
}
Should you test such components. All i can test is if it renders , right ? I've heard about snapshot testing , but i'm not sure if this is a case where i should use it.

I do not think that there is a right answer for that but think about the value of the test always from the user's point of view.
Are you planning to change this to support translations? so it would be a good test by snapshot or just checking the labels on the page.
Does the snapshot test make sense for your team? or they would just update when get some error?
But the most important from my point of view (and the user) would be the style, a CSS change would be able to break the style of this component so you could think to support visual tests focused only on the whole pages to cover those scenarios, it takes a real screenshot to compare the images.

Related

How to solve react hydration error in Nextjs

I have created small nextjs page using wordpress REST API, Now react-hydration-error error show this page.I am using react html parser npm. How do I solve this error. could you please solve this error.
my code:
import Image from 'next/image'
import React ,{Component}from 'react'
import Link from 'next/link';
import { BiCalendar } from "react-icons/bi";
import ReactHtmlParser from 'react-html-parser';
export default class Blog extends Component{
constructor(props){
super(props);
this.state={
data: props.bloglist,
isLoading: true,
dataLoaded: false,
};
}
render(){
if (!this.state.data) {
return null;
}
console.log(this.state.data)
return(
<>
<div className="container blog-section">
<div className='row'>
<h2>Latest Posts</h2>
</div>
<div className='row'>
{
this.state.data.map(((x,i) =>(
<div className='col-md-4 boxs text-center' key={i}>
<div className='bg-info'>
<img src={x.images.large} className='img-fluid'/>
<h3>{x.title.rendered} </h3>
<p className='shopping'><span><BiCalendar/> {x.date}</span> </p>
{/* <p dangerouslySetInnerHTML={{__html: x.excerpt.rendered}}></p><span><BiShoppingBag/> {x.slug}</span> */}
<p class='expert'>{ReactHtmlParser(x.excerpt.rendered)}</p>
<Link href={"/blog"+"/"+x.slug+"/"+x.id } passHref={true}><p className='readmore'><span>Readmore </span></p></Link>
</div>
</div>
)))
}
</div>
</div>
</>
)
}
}
My original issues:
paragraph coming this format <p>If you have heard that there are ways to make money while shopping in the UAE and would lik</p> from API, So I converted to html.
I had this error, in my case I had <p> tag nested inside another <p> tag,
I was using Typography (MUI v5) to render text, switching to <Box> from <Typography> fixed the error.
We use components to build the React-based websites, These components are made using HTML tags. It is very important not to nest the same HTML elements.
For Example:
function Logo() {
return (
<Link href="/">
<a>
<Image
src="/images/logo.svg"
width={100}
height={75}
/>
</a>
</Link>
);
}
export default Logo;
Above is the Logo Component which has already the <a></a> tag inside it.
In this example, you will get the React Hydration Error if the <a> tag is used inside another <a> tag.
<a href="#">
<Logo />
</a>
So do not include the same HTML tags, which are hidden inside the
components to avoid react hydration error.
In my case I am using NextJS and I had a dropdown with react-select, the default value was changing after a small calculation, that does not like to nextjs, this is my previous code:
<Select options={seasons}
onChange={() => setSeason(e.value)}
defaultValue={seasons.find((x) => x.value == season) ? seasons.find((x) => x.value == season) : seasons[0]}
/>
So, I changed that calculation to the useEffect and initialized the react-select dropdown only when that value was calculated,now this is my current code that works:
{defaultSeason && (<Select options={seasons}
onChange={() => setSeason(e.value)}
defaultValue={defaultSeason}
/>)}
So, basically check that the defaultValue or anything else does not change after the html is sent to the client part in NextJS.
Follow these: https://nextjs.org/docs/messages/react-hydration-error
Or try deleting <a> within <Link> maybe.
My first code was this:
const isUserLoggedIn = is_user_logged_in()
// is_user_logged_in() checks for cookie of user token and returns boolean
Got the error about hydration
Then changed code to this:
const [isUserLoggedIn, setIsUserLoggedIn] = useState(null)
useEffect(() => {
setIsUserLoggedIn(is_user_logged_in())
}, [])
Renders was like this:
{isUserLoggedIn ? (
<>
{/* After login */}
<Profile USER={USER}/>
</>
) : (
<>
{/* Before login */}
<SigninButtons/>
</>
)}
And error solved
You can also check this
https://nextjs.org/docs/messages/react-hydration-error
Just try restarting the server. npm run dev. It worked for me. I was using react-hot-toaster.
Also try to check if you have sth like this:
<p>
<div>
Hello
</div>
</p>
div cant be inside p tag

how to resolve "Prop `id` did not match. Server: "react-tabs-30" Client: "react-tabs-0" console issue?

i am trying tab in next in next.js, but every time i use it it show a console warning link this Prop `id` did not match. Server: "react-tabs-30" Client: "react-tabs-0", i know it isn't effect my app but it is so annoying. how to solve this waring
<Tabs>
<div className="tab-controler ml-sm-auto">
<TabList className="tab-lists list-inline d-flex flex-wrap nav mb-3" style={{ background: '#F8F8F8' }}>
<Tab className={`${CostCalculatorStyle.PEItem} tab-lists__item`}>Buy & Ship for me</Tab>
<Tab className={`${CostCalculatorStyle.PEItem} tab-lists__item`}>Ship for me</Tab>
</TabList>
</div>
<TabPanel key={"tabpanel_ship"}>
<div className="row">
<div className="col-lg-6">
<ShipForMeForm handleFormValue={handleFormValue} handleProductValue={handleProducts} handleRef={handleRef} />
</div>
<div className="col-lg-6 align-self-center">
<div className="costcalc-empty-thumb text-center">
<Image
src="/assets/topNavbarPages/costCalculator.svg"
alt="Cost Calculator"
width="469"
height="288"
/>
</div>
</div>
</div>
</TabPanel>
<TabPanel key={"tabpanel_buy_ship"}>
<div className="row">
<div className="col-lg-6">
<ShipForMeForm handleFormValue={handleFormValue} handleProductValue={handleProducts} handleRef={handleRef} />
</div>
<div className="col-lg-6 align-self-center">
<div className="costcalc-empty-thumb text-center">
<Image
src="/assets/topNavbarPages/costCalculator.svg"
alt="Cost Calculator"
width="469"
height="288"
/>
</div>
</div>
</div>
</TabPanel>
</Tabs>
as you can see i use react-tabs for tab but i also work on react js where i use the same code but it didn't show this console warning. so my question is why it is happing? and how i can solve it ?
In next js i fixed it like that
import dynamic from 'next/dynamic'
const Tabs = dynamic(import('react-tabs').then(mod => mod.Tabs), { ssr: false }) // disable ssr
import { Tab, TabList, TabPanel } from 'react-tabs'
it work for me
The best solution I know of is just to set the id yourself in the <Tabs> component. Ex: <Tabs id={1}>
See https://github.com/chakra-ui/chakra-ui/issues/4328#issuecomment-890525420 for more details and examples.
NextJs generating code in server side as you know.
This error means that something on the server is different from the Client. This can happen if the client does a re-render.
For example.
export default function Test(props) {
return (
<>
<span>{props.name}</span>
</>
);
}
I have this simple Test component.And I send name (1) prop from another component to this Test component. And if I change this name (to 2) in client using redux (for example I have another name in my redux store) after page generated I get this error.
props did not match server "1" client "2"
To solve this error I need to just not change this name with redux after page generated in server. The data can be change only with user manipulations after page rendered in server.
Same thing happened to me when I use Tabs from react-bootstrap. Koushik Saha's answer can be apply for that also but with a small change. Need to put react-bootstrap instead react-tabs
const Tabs = dynamic(import('react-bootstrap').then(mod => mod.Tabs), { ssr: false })
In case you miss it
If you are using Nextjs + Material-ui, there are actually custom codes that you can/need to include in your _document.js and _app.js to remove the server-side injected CSS so the CSS is recreated when page loads.
As codes changes with mui's and nextjs' version, i will refer you to the repository directly
https://github.com/mui-org/material-ui/tree/master/examples/nextjs/pages
As per the documentation in the react-tabs repo/npmjs.org page (https://www.npmjs.com/package/react-tabs):
import { resetIdCounter } from 'react-tabs';
resetIdCounter();
ReactDOMServer.renderToString(...);
I was having the same issue and called the resetIdCounter function inside my parent component to the tabs structure and cleared up the error.
Not sure if maybe there is a better place to use this function, like maybe in a useEffect hook or something, but I'm going with this for now.

Avoid component update while changing state vaiable

Background
I have a React component which includes further two more components. I component includes a chart(build with react-charts) and the other is a simple input field. I initially make not visible but it become visible when someone clicks icon over there.
Issue, child rerenders when state changes
Now the problem is whenever I toggle this input field it automatically refreshes my graph. In fact when I type into my input field it also refreshes the graph. I think it rerenderes the graph as I update the state variable. I want to stop this behavior. Any suggestions on how can I do this.
Component Screenshot(https://i.imgur.com/zeCQ6FC.png)
Component Code
<div className="row">
<DealGraph ref={this.dealRef} />
<div className="col-md-4">
<div className="row">
<div style={style} className="col-md-12 bg-white border-radius-10 default-shadow">
<h3 className="sub-heading roboto" style={border}>
Create Deals
</h3>
<input
type="text"
name="deal"
className="form-control mgt-30"
value="Deal One"
readOnly
/>
<button
type="button"
onClick={this.showAddBlock}
style={button}
className="golden-button create-deal-button"
>
<i className="fa fa-plus"></i>
</button>
{addDealStatus ? (
<div className="col-md-12 add-deal-box pd-0-0">
<input
type="text"
className="form-control mgt-30 mgb-10"
name="add-deals"
placeholder="Add Deals"
/>
<button type="button" className="golden-button flex all-center">
Add
</button>
</div>
) : null}
</div>
</div>
</div>
</div>
Toggle function
showAddBlock=() => {
this.setState({addDealStatus:!this.state.addDealStatus})
}
use PureComponent
To stop a child component rerendering from it parent you should make the child a pure component.
import React from 'react';
class DealGraph extends React.PureComponent { // notice PureComponent
render() {
const { label, score = 0, total = Math.max(1, score) } = this.props;
return (
<div>
/* Your graph code */
</div>
)
}
}
Use the { pure } HOC from Recompose
You can use a functional component that is wrapped in the pure HOC from recompose
import React from 'react';
import { pure } from 'recompose';
function DealGraph(props) {
return (
<div>
/* Your graph code */
</div>
)
}
export default pure(DealGraph); // notice pure HOC
A quick solution would be to move the input to an own component.
A more sophisticated solution is adapting the shouldComponentUpdate function in your DealGraphcomponent like stated here React: Parent component re-renders all children, even those that haven't changed on state change
By Default while rendering every component react checks for shouldComponentUpdate .React Components dont implement shouldComponentUpdate by default.So either we can implement a shouldComponentUpdate. Or Make the child class as a pure component.

Why is my react-lazyload component not working?

Up until a few days ago, my implementation of LazyLoad was working perfectly, but now I can't seem to get it to work.
This is my component:
import React from 'react';
import LazyLoad from 'react-lazyload';
import './image.scss';
const Image = image => (
<LazyLoad height={200} offset={100} once>
<div
className="image-container"
orientation={image.orientation}>
<img
className="image"
src={image.url}
alt={image.alt}
/>
{'caption' in image &&
<div className="meta">
<p className="caption">{image.caption}</p>
<p className="order">{image.currentNumber}/{image.maxNumber}</p>
</div>
}
</div>
</LazyLoad>
)
export default Image
And in App.js it is called like this:
render() {
return (
<div className="wrapper">
<GalleryTop details={this.state.gallery_top} />
{this.state.images.map((image, index) => <Image key={index} {...image} /> )}
</div>
)
}
But it won't work! Here's the demo environment:
https://gifted-kare-1c0eba.netlify.com/
(Check Network tab in Inspector to see that images are all requested from initial load)
There's also a video here
Any idea about what I am doing wrong?
Thanks in advance,
Morten
I ran into similar issues with the npm package react-lazyload. For one, this package only allows one child per LazyLoad component, so you would have to rearrange your hierarchy to make it work. Secondly, I found some strange behaviors when loading images that were already set within the viewport. The documentation does list import {forceCheck} from 'react-lazyload'; combined with forceCheck(); as a means of manually checking the elements, but I found this inconvenient and insufficient for components that aren't rerendering.
I was able to obtain the exact same functionalities with an easier implementation from the alternative package react-lazy-load. Mind the hyphen. This package also requires node>0.14. More or less, it does the same thing. You can read their documentation here: react-lazy-load

Error React.Children.only expected to receive a single React element child

Not entirely sure what went wrong in my app here. I'm using create-react-app, and I'm trying to render all of my components into the respective root div. Problem is, I'm able to render all of the components onto the page except the very last one, the Score component. I've even tried throwing that component into a div and I'm still getting the following issue:
'React.Children.only expected to receive a single React element child'.
What exactly does this mean?
Here's my App.js structure.
render() {
return (
<div className="App">
<div className="App-header">
<h2>BAO BAO BAO</h2>
</div>
{this.state.result ? this.renderResult() : this.renderTest()}
<Baoquestion />
<AnswerChoices />
<BaoScore />
<Score />
</div>
);
}
export default App;
Content of Score.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
function Score(props) {
return (
<div>
<CSSTransitionGroup
className="container result"
transitionName="test"
transitionEnterTimeout={500}
transitionLeaveTimeout={300}>
>
<div>
You prefer <strong>{props.testScore}</strong>!
</div>
</CSSTransitionGroup>
</div>
);
}
Score.propTypes = {
quizResult: PropTypes.string,
};
export default Score;
From react-transition-group documentation:
You must provide the key attribute for all children of CSSTransitionGroup, even when only rendering a single item. This is how React will determine which children have entered, left, or stayed.
Please then add a key, even a static one, for the component you render inside the transition group:
<CSSTransitionGroup
className="container result"
transitionName="test"
transitionEnterTimeout={500}
transitionLeaveTimeout={300}>
>
<div key="transition-group-content" >
You prefer <strong>{props.testScore}</strong>!
</div>
</CSSTransitionGroup>
I had the same error using CSS Transitions. What worked for me is to use these React tags: <></> to wrap around the tags inside the css transition tags.
Notice I have two tags inside TransitionGroup and CSSTransition tags like so:
<TransitionGroup>
<CSSTransition key={quotesArr[active]}>
<>
<p>{current.quote}</p>
<h2>{current.client}</h2>
</>
</CSSTransition>
</TransitionGroup>
<CSSTransitionGroup
className="container result"
transitionName="test"
transitionEnterTimeout={500}
transitionLeaveTimeout={300}>
> ^ ** Must be a typo here **
^ ** Remove this '>' typo solve my problem **
The root cause of this error 'Error React.Children.only expected to receive a single React element child' is that there are two '>' in the ending of the JSX code. Remove one of the '>' solved this issue.

Resources